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 RadioButtonSize = 'sm' | 'md' | 'lg';
export type RadioButtonVariant = 'primary' | 'secondary' | 'success' | 'warning' | 'danger';
export type RadioButtonState = 'default' | 'error' | 'disabled';

export interface RadioButtonData {
  value: string;
  label: string;
  disabled?: boolean;
  description?: string;
}

@Component({
  selector: 'ui-radio-button',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [CommonModule],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => RadioButtonComponent),
      multi: true
    }
  ],
  template: `
    <div class="radio-button-wrapper" [class]="getWrapperClasses()">
      <label class="radio-button-container" [for]="radioId">
        <div class="radio-button" [class]="getRadioClasses()">
          <input
            type="radio"
            class="radio-button__input"
            [id]="radioId"
            [name]="name"
            [value]="value"
            [checked]="isChecked()"
            [disabled]="disabled"
            [required]="required"
            (change)="onSelectionChange($event)"
            (focus)="onFocus($event)"
            (blur)="onBlur($event)"
          />
          <div class="radio-button__circle">
            <div class="radio-button__inner-circle" [class.radio-button__inner-circle--selected]="isChecked()"></div>
          </div>
        </div>
        
        <div class="radio-button-content" [class]="getContentClasses()">
          <div class="radio-button__label">{{ label }}</div>
          @if (description) {
            <div class="radio-button__description">{{ description }}</div>
          }
        </div>
      </label>
      
      @if (helperText && !error) {
        <div class="radio-button__helper-text">{{ helperText }}</div>
      }
      
      @if (error) {
        <div class="radio-button__error-text">{{ error }}</div>
      }
    </div>
  `,
  styleUrls: ['./radio-button.component.scss']
})
export class RadioButtonComponent implements ControlValueAccessor {
  @Input() value: string = '';
  @Input() label: string = '';
  @Input() name: string = '';
  @Input() size: RadioButtonSize = 'md';
  @Input() variant: RadioButtonVariant = 'primary';
  @Input() state: RadioButtonState = 'default';
  @Input() disabled = false;
  @Input() required = false;
  @Input() description: string = '';
  @Input() helperText: string = '';
  @Input() error: string = '';
  @Input() radioId: string = `radio-${Math.random().toString(36).substr(2, 9)}`;

  @Output() selectionChange = new EventEmitter<string>();
  @Output() radioFocus = new EventEmitter<FocusEvent>();
  @Output() radioBlur = new EventEmitter<FocusEvent>();

  private selectedValue = signal<string>('');
  private focused = signal<boolean>(false);

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

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

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

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

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

  isChecked(): boolean {
    return this.selectedValue() === this.value;
  }

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

    if (this.disabled) classes.push('radio-button-wrapper--disabled');
    if (this.focused()) classes.push('radio-button-wrapper--focused');
    if (this.isChecked()) classes.push('radio-button-wrapper--checked');
    if (this.error) classes.push('radio-button-wrapper--error');
    if (this.description) classes.push('radio-button-wrapper--has-description');

    return classes.join(' ');
  }

  getRadioClasses(): string {
    const classes: string[] = [];

    if (this.isChecked()) classes.push('radio-button--checked');
    if (this.disabled) classes.push('radio-button--disabled');

    return classes.join(' ');
  }

  getContentClasses(): string {
    const classes: string[] = [];

    if (this.description) classes.push('radio-button-content--has-description');

    return classes.join(' ');
  }

  onSelectionChange(event: Event): void {
    const target = event.target as HTMLInputElement;
    if (target.checked) {
      this.selectedValue.set(this.value);
      this.onChange(this.value);
      this.selectionChange.emit(this.value);
    }
  }

  onFocus(event: FocusEvent): void {
    this.focused.set(true);
    this.radioFocus.emit(event);
  }

  onBlur(event: FocusEvent): void {
    this.focused.set(false);
    this.onTouched();
    this.radioBlur.emit(event);
  }
}