import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy, forwardRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

export type SelectSize = 'small' | 'medium' | 'large';
export type SelectVariant = 'outlined' | 'filled';

export interface SelectOption {
  value: any;
  label: string;
  disabled?: boolean;
}

@Component({
  selector: 'ui-select',
  standalone: true,
  imports: [CommonModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => SelectComponent),
      multi: true
    }
  ],
  template: `
    <div [class]="wrapperClasses">
      @if (label) {
        <label [for]="selectId" class="select-label">
          {{ label }}
          @if (required) {
            <span class="select-required">*</span>
          }
        </label>
      }
      
      <div class="select-container">
        <select
          [id]="selectId"
          [disabled]="disabled"
          [value]="value"
          [class]="selectClasses"
          (change)="onSelectionChange($event)"
          (blur)="onBlur()"
          (focus)="onFocus()"
        >
          @if (placeholder) {
            <option value="" disabled>{{ placeholder }}</option>
          }
          
          @for (option of options; track option.value) {
            <option 
              [value]="option.value" 
              [disabled]="option.disabled"
            >
              {{ option.label }}
            </option>
          }
        </select>
        
        <div class="select-arrow">
          <svg width="12" height="8" viewBox="0 0 12 8" fill="none">
            <path d="M1 1L6 6L11 1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
        
        @if (helperText && !errorText) {
          <div class="select-helper-text">{{ helperText }}</div>
        }
        
        @if (errorText) {
          <div class="select-error-text">{{ errorText }}</div>
        }
      </div>
    </div>
  `,
  styleUrl: './select.component.scss'
})
export class SelectComponent implements ControlValueAccessor {
  @Input() label: string = '';
  @Input() placeholder: string = '';
  @Input() helperText: string = '';
  @Input() errorText: string = '';
  @Input() size: SelectSize = 'medium';
  @Input() variant: SelectVariant = 'outlined';
  @Input() disabled: boolean = false;
  @Input() required: boolean = false;
  @Input() fullWidth: boolean = false;
  @Input() options: SelectOption[] = [];

  @Output() valueChange = new EventEmitter<any>();
  @Output() focused = new EventEmitter<void>();
  @Output() blurred = new EventEmitter<void>();

  value: any = '';
  selectId = `ui-select-${Math.random().toString(36).substr(2, 9)}`;

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

  writeValue(value: any): void {
    this.value = value;
  }

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

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

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

  get wrapperClasses(): string {
    return [
      'ui-select',
      `ui-select--${this.size}`,
      `ui-select--${this.variant}`,
      this.disabled ? 'ui-select--disabled' : '',
      this.errorText ? 'ui-select--error' : '',
      this.fullWidth ? 'ui-select--full-width' : ''
    ].filter(Boolean).join(' ');
  }

  get selectClasses(): string {
    return [
      'select-field',
      this.errorText ? 'select-field--error' : ''
    ].filter(Boolean).join(' ');
  }

  onSelectionChange(event: Event): void {
    const target = event.target as HTMLSelectElement;
    this.value = target.value;
    this.onChange(this.value);
    this.valueChange.emit(this.value);
  }

  onFocus(): void {
    this.focused.emit();
  }

  onBlur(): void {
    this.onTouched();
    this.blurred.emit();
  }
}