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

export type CheckboxSize = 'sm' | 'md' | 'lg';
export type CheckboxVariant = 'primary' | 'secondary' | 'success' | 'warning' | 'danger';
export type CheckboxState = 'default' | 'error' | 'disabled';

@Component({
  selector: 'ui-checkbox',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [CommonModule],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CheckboxComponent),
      multi: true
    }
  ],
  template: `
    <label class="checkbox-wrapper" [class]="getWrapperClasses()" [attr.aria-disabled]="disabled">
      <input
        type="checkbox"
        class="checkbox-input"
        [id]="checkboxId"
        [checked]="isChecked()"
        [disabled]="disabled"
        [required]="required"
        [attr.aria-describedby]="description ? checkboxId + '-desc' : null"
        (change)="onCheckboxChange($event)"
        (focus)="onFocus($event)"
        (blur)="onBlur($event)"
      />
      <div class="checkbox-control" [class]="getControlClasses()">
        <div class="checkbox-checkmark" [class.checkbox-checkmark--checked]="isChecked()">
          <svg class="checkbox-icon" viewBox="0 0 16 16" fill="none">
            <path d="M13.5 4.5L6 12L2.5 8.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
      </div>
      
      @if (label || description) {
        <div class="checkbox-content" [class]="getContentClasses()">
          @if (label) {
            <div class="checkbox-label" [class.checkbox-label--required]="required">
              {{ label }}
              @if (required) {
                <span class="checkbox-required-indicator">*</span>
              }
            </div>
          }
          @if (description) {
            <div class="checkbox-description" [id]="checkboxId + '-desc'">{{ description }}</div>
          }
        </div>
      }
    </label>
  `,
  styleUrls: ['./checkbox.component.scss']
})
export class CheckboxComponent implements ControlValueAccessor {
  @Input() label: string = '';
  @Input() description: string = '';
  @Input() size: CheckboxSize = 'md';
  @Input() variant: CheckboxVariant = 'primary';
  @Input() state: CheckboxState = 'default';
  @Input() disabled = false;
  @Input() required = false;
  @Input() checkboxId: string = `checkbox-${Math.random().toString(36).substr(2, 9)}`;

  @Output() checkboxChange = new EventEmitter<boolean>();
  @Output() checkboxFocus = new EventEmitter<FocusEvent>();
  @Output() checkboxBlur = new EventEmitter<FocusEvent>();

  private checked = signal<boolean>(false);

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

  isChecked(): boolean {
    return this.checked();
  }

  writeValue(value: boolean): void {
    this.checked.set(!!value);
  }

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

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

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

  getWrapperClasses(): string {
    const classes = [
      `checkbox-wrapper--${this.size}`,
      `checkbox-wrapper--${this.variant}`,
      `checkbox-wrapper--${this.state}`
    ];

    if (this.disabled) classes.push('checkbox-wrapper--disabled');
    if (this.isChecked()) classes.push('checkbox-wrapper--checked');
    if (this.description) classes.push('checkbox-wrapper--with-description');

    return classes.join(' ');
  }

  getControlClasses(): string {
    const classes = [
      `checkbox-control--${this.size}`,
      `checkbox-control--${this.variant}`,
      `checkbox-control--${this.state}`
    ];

    if (this.disabled) classes.push('checkbox-control--disabled');
    if (this.isChecked()) classes.push('checkbox-control--checked');

    return classes.join(' ');
  }

  getContentClasses(): string {
    const classes = [
      `checkbox-content--${this.size}`
    ];

    if (this.disabled) classes.push('checkbox-content--disabled');

    return classes.join(' ');
  }

  onCheckboxChange(event: Event): void {
    const target = event.target as HTMLInputElement;
    const value = target.checked;
    
    this.checked.set(value);
    this.onChange(value);
    this.checkboxChange.emit(value);
  }

  onFocus(event: FocusEvent): void {
    this.checkboxFocus.emit(event);
  }

  onBlur(event: FocusEvent): void {
    this.onTouched();
    this.checkboxBlur.emit(event);
  }
}