import { Component, input, output, signal, computed } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TranslateModule } from '@ngx-translate/core';
import {
  PRODUCT_COLORS,
  getColorHex,
  ColorCategory,
  ColorOption,
} from '../../../core/constants/colors.const';
import { VariantOption } from '../../../features/calculator/services/quote-estimator.service';

@Component({
  selector: 'app-color-selector',
  standalone: true,
  imports: [CommonModule, TranslateModule],
  templateUrl: './color-selector.component.html',
  styleUrl: './color-selector.component.scss',
})
export class ColorSelectorComponent {
  selectedColor = input<string>('Black');
  selectedVariantId = input<number | null>(null);
  variants = input<VariantOption[]>([]);
  colorSelected = output<{ colorName: string; filamentVariantId?: number }>();

  isOpen = signal(false);

  categories = computed(() => {
    const vars = this.variants();
    if (vars && vars.length > 0) {
      const byFinish = new Map<string, ColorOption[]>();
      vars.forEach((v) => {
        const finish = v.finishType || 'AVAILABLE_COLORS';
        const bucket = byFinish.get(finish) || [];
        bucket.push({
          label: v.colorName,
          value: v.colorName,
          hex: v.hexColor,
          variantId: v.id,
          outOfStock: v.isOutOfStock,
        });
        byFinish.set(finish, bucket);
      });

      return Array.from(byFinish.entries()).map(([finish, colors]) => ({
        name: finish,
        colors,
      })) as ColorCategory[];
    }
    return PRODUCT_COLORS;
  });

  toggleOpen() {
    this.isOpen.update((v) => !v);
  }

  selectColor(color: ColorOption) {
    if (color.outOfStock) return;

    this.colorSelected.emit({
      colorName: color.value,
      filamentVariantId: color.variantId,
    });
    this.isOpen.set(false);
  }

  // Helper to find hex for the current selected value
  getCurrentHex(): string {
    // Check in dynamic variants first
    const vars = this.variants();
    if (vars && vars.length > 0) {
      const found = vars.find((v) => v.colorName === this.selectedColor());
      if (found) return found.hexColor;
    }

    return getColorHex(this.selectedColor());
  }

  close() {
    this.isOpen.set(false);
  }
}
