import { Component, Input, Output, EventEmitter, forwardRef } from '@angular/core';

import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'ccl-input',
  standalone: true,
  imports: [],
  templateUrl: './input.html',
  styleUrls: ['./input.css'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => InputComponent),
      multi: true
    }
  ]
})
export class InputComponent implements ControlValueAccessor {
  @Input() type: 'text' | 'password' | 'number' | 'email' = 'text';
  @Input() label = '';
  @Input() placeholder = '';
  @Input() disabled = false;
  @Input() readonly = false;
  @Input() error = false;
  @Input() errorMessage = '';
  @Input() helperText = '';
  @Input() required = false;
  @Input() ariaLabel?: string;
  @Input() ariaDescribedBy?: string;
  @Input() minLength?: number;
  @Input() maxLength?: number;
  /** Native `min` attribute (e.g. number, date, time inputs). */
  @Input() min?: string | number;
  /** Native `max` attribute (e.g. number, date, time inputs). */
  @Input() max?: string | number;

  @Output() valueChange = new EventEmitter<string>();

  id = 'ccl-input-' + Math.random().toString(36).substring(2, 9);
  value = '';

  // ControlValueAccessor implementation
  private onChange = (value: string) => {};
  private onTouched = () => {};

  writeValue(value: string): void {
    this.value = value || '';
  }

  registerOnChange(fn: (value: string) => void): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }

  onInput(event: Event): void {
    const target = event.target as HTMLInputElement;
    this.value = target.value;
    this.onChange(this.value);
    this.valueChange.emit(this.value);
    this.onTouched();
  }

  get inputId(): string {
    return this.id;
  }

  get labelId(): string {
    return `${this.id}-label`;
  }

  get hintId(): string {
    return `${this.id}-hint`;
  }

  get errorId(): string {
    return `${this.id}-error`;
  }

  get describedBy(): string | undefined {
    const ids = [];
    if (this.ariaDescribedBy) {
      ids.push(this.ariaDescribedBy);
    }
    if (this.helperText) {
      ids.push(this.hintId);
    }
    if (this.error && this.errorMessage) {
      ids.push(this.errorId);
    }
    return ids.length > 0 ? ids.join(' ') : undefined;
  }

  get ariaAttributes(): { [key: string]: any } {
    const attrs: { [key: string]: any } = {};
    
    if (this.ariaLabel) {
      attrs['aria-label'] = this.ariaLabel;
    }
    
    if (this.describedBy) {
      attrs['aria-describedby'] = this.describedBy;
    }
    
    attrs['aria-invalid'] = this.error;
    attrs['aria-required'] = this.required;
    
    return attrs;
  }
}
