import { Component, Input, forwardRef, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, ReactiveFormsModule } from '@angular/forms';
import { TabFormField } from '../../../interfaces/generic-tab-form.interface';

interface ColorOption {
  name: string;
  code: string;
}

@Component({
  selector: 'app-color-input',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => ColorInputComponent),
      multi: true
    }
  ],
  template: `
    <div class="color-input-container">
      <label *ngIf="field?.label" [for]="fieldId" class="color-label">
        {{ field?.label }}
        <span *ngIf="field?.required" class="required-indicator">*</span>
      </label>
      
      <div class="color-selection-wrapper">
        <!-- Color Select Button -->
        <button 
          type="button"
          class="color-select-button"
          [class.open]="isDropdownOpen"
          (click)="toggleDropdown()"
          [id]="fieldId"
        >
          <div class="select-content">
            <div *ngIf="selectedColor; else placeholderTemplate" class="selected-display">
              <div 
                class="selected-circle"
                [style.background-color]="selectedColor.code"
              ></div>
              <span class="selected-name">{{ selectedColor.name }}</span>
            </div>
            <ng-template #placeholderTemplate>
              <span class="placeholder">Selecione uma cor</span>
            </ng-template>
          </div>
          <i class="fas fa-chevron-down dropdown-arrow" [class.rotated]="isDropdownOpen"></i>
        </button>

        <!-- Dropdown with Color Grid -->
        <div class="color-dropdown" [class.open]="isDropdownOpen">
          <div class="color-grid">
            <div 
              *ngFor="let option of colorOptions" 
              class="color-option"
              [class.selected]="isSelected(option)"
              (click)="selectColor(option)"
              [title]="option.name"
            >
              <div 
                class="color-circle"
                [style.background-color]="option.code"
              ></div>
              <span class="color-name">{{ option.name }}</span>
            </div>
          </div>
          
          <!-- Clear button no dropdown -->
          <div *ngIf="selectedColor" class="dropdown-actions">
            <button 
              type="button" 
              class="clear-btn"
              (click)="clearSelection()"
              title="Limpar seleção"
            >
              <i class="fas fa-times"></i>
              Limpar
            </button>
          </div>
        </div>
      </div>
      
      <!-- Overlay para fechar dropdown ao clicar fora -->
      <div 
        *ngIf="isDropdownOpen" 
        class="dropdown-overlay"
        (click)="closeDropdown()"
      ></div>
    </div>
  `,
  styleUrls: ['./color-input.component.scss']
})
export class ColorInputComponent implements ControlValueAccessor, OnInit {
  @Input() field?: TabFormField;
  
  fieldId = `color-input-${Math.random().toString(36).substr(2, 9)}`;
  selectedColor: ColorOption | null = null;
  colorOptions: ColorOption[] = [];
  isDropdownOpen = false;
  
  private onChange = (value: any) => {};
  private onTouched = () => {};

  ngOnInit() {
    // Extrair opções de cor do field
    if (this.field?.options) {
      this.colorOptions = this.field.options.map(opt => opt.value as ColorOption);
    }
  }

  selectColor(color: ColorOption) {
    this.selectedColor = color;
    this.onChange(color);
    this.onTouched();
    this.closeDropdown();
  }

  clearSelection() {
    this.selectedColor = null;
    this.onChange(null);
    this.onTouched();
    this.closeDropdown();
  }

  toggleDropdown() {
    this.isDropdownOpen = !this.isDropdownOpen;
    if (this.isDropdownOpen) {
      this.onTouched();
    }
  }

  closeDropdown() {
    this.isDropdownOpen = false;
  }

  isSelected(color: ColorOption): boolean {
    if (!this.selectedColor) return false;
    return this.selectedColor.name === color.name && this.selectedColor.code === color.code;
  }

  // ControlValueAccessor implementation
  writeValue(value: any): void {
    console.log('🎨 [ColorInput] writeValue chamado com:', value);
    console.log('🎨 [ColorInput] Tipo do valor:', typeof value);
    console.log('🎨 [ColorInput] JSON do valor:', JSON.stringify(value));
    
    if (!value) {
      this.selectedColor = null;
      console.log('❌ [ColorInput] Valor vazio, selectedColor = null');
      return;
    }

    // 🎯 CASO 1: Objeto completo { name, code }
    if (typeof value === 'object' && value.name && value.code) {
      this.selectedColor = value;
      console.log('✅ [ColorInput] Objeto completo reconhecido:', this.selectedColor);
      return;
    }

    // 🎯 CASO 2: String com nome da cor (ex: "BRANCA")
    if (typeof value === 'string') {
      const colorFromString = this.findColorByName(value);
      if (colorFromString) {
        this.selectedColor = colorFromString;
        console.log('✅ [ColorInput] String convertida para objeto:', this.selectedColor);
        return;
      }
    }

    // 🎯 CASO 3: Objeto com apenas name (sem code)
    if (typeof value === 'object' && value.name && !value.code) {
      const colorFromName = this.findColorByName(value.name);
      if (colorFromName) {
        this.selectedColor = colorFromName;
        console.log('✅ [ColorInput] Objeto incompleto completado:', this.selectedColor);
        return;
      }
    }

    // 🎯 FALLBACK: Não conseguiu processar
    this.selectedColor = null;
    console.log('❌ [ColorInput] Valor não reconhecido, selectedColor = null');
  }

  /**
   * 🎯 Encontra uma cor pelo nome nas opções disponíveis
   */
  private findColorByName(colorName: string): ColorOption | null {
    if (!colorName) return null;
    
    const normalizedName = colorName.trim().toUpperCase();
    
    // Procura nas opções disponíveis do formulário
    const foundOption = this.colorOptions.find(option => 
      option.name.toUpperCase() === normalizedName
    );
    
    if (foundOption) {
      console.log('🎯 [ColorInput] Cor encontrada nas opções:', foundOption);
      return foundOption;
    }
    
    console.log('❌ [ColorInput] Cor não encontrada nas opções:', colorName);
    return null;
  }

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

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

  setDisabledState(isDisabled: boolean): void {
    // Implementar se necessário
  }
} 