import { Component, Input, ContentChild, ElementRef, AfterContentInit, AfterViewInit, ChangeDetectorRef } from '@angular/core';


@Component({
  selector: 'ccl-form-field-wrapper',
  standalone: true,
  imports: [],
  templateUrl: './form-field-wrapper.html',
  styleUrls: ['./form-field-wrapper.css']
})
export class FormFieldWrapperComponent implements AfterContentInit, AfterViewInit {
  @Input() label: string = '';
  @Input() required: boolean = false;
  @Input() hint: string = '';
  @Input() error: string = '';
  @Input() state: 'default' | 'error' | 'success' | 'disabled' = 'default';
  @Input() for: string = '';

  @ContentChild('input') inputElement?: ElementRef<HTMLInputElement>;

  private _uniqueId: string = 'ccl-form-field-' + Math.random().toString(36).substring(2, 9);
  
  constructor(private cdr: ChangeDetectorRef) {}
  
  get fieldId(): string {
    return this.for || this._uniqueId;
  }

  get hintId(): string {
    return this.fieldId + '-hint';
  }

  get errorId(): string {
    return this.fieldId + '-error';
  }

  get describedBy(): string {
    const ids: string[] = [];
    if (this.hint) ids.push(this.hintId);
    if (this.error) ids.push(this.errorId);
    return ids.join(' ');
  }

  get isErrorState(): boolean {
    return this.state === 'error' || !!this.error;
  }

  get isSuccessState(): boolean {
    return this.state === 'success' && !this.isErrorState;
  }

  get isDisabledState(): boolean {
    return this.state === 'disabled';
  }

  ngAfterContentInit(): void {
    this.updateInputAttributes();
  }

  ngAfterViewInit(): void {
    this.updateInputAttributes();
  }

  private updateInputAttributes(): void {
    // Use setTimeout to ensure the DOM is ready
    setTimeout(() => {
      const input = this.inputElement?.nativeElement;
      if (input) {
        // Set the ID if not already set
        if (!input.id) {
          input.id = this.fieldId;
        }
        
        // Set ARIA attributes
        if (this.describedBy) {
          input.setAttribute('aria-describedby', this.describedBy);
        } else {
          input.removeAttribute('aria-describedby');
        }
        
        if (this.required) {
          input.setAttribute('aria-required', 'true');
        } else {
          input.removeAttribute('aria-required');
        }
        
        if (this.isErrorState) {
          input.setAttribute('aria-invalid', 'true');
        } else {
          input.removeAttribute('aria-invalid');
        }
      }
    }, 0);
  }
}
