import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { TranslatePipe } from '../../../../../i18n/translate.pipe';
import { IconComponent } from '../../../../../shared/ui/icon/icon.component';

export interface VariantOption {
  value: string;
  label?: string;
}

export interface VariantOptionGroup {
  key: string;
  label: string;
  options: VariantOption[];
}

@Component({
  selector: 'app-product-variant-selector',
  standalone: true,
  imports: [TranslatePipe, IconComponent],
  templateUrl: './variant-selector.component.html',
  styleUrls: ['./variant-selector.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProductVariantSelectorComponent {
  @Input() optionGroups: VariantOptionGroup[] = [];
  @Input() selectedOptions: Record<string, string> = {};

  @Input() colours: string[] = [];
  @Input() sizes: string[] = [];
  @Input() selectedColour: string | null = null;
  @Input() selectedSize: string | null = null;
  @Input() fallbackColour: string | null = null;
  @Input() fallbackSize: string | null = null;

  @Output() optionSelected = new EventEmitter<{ groupKey: string; value: string }>();
  @Output() colourSelected = new EventEmitter<string>();
  @Output() sizeSelected = new EventEmitter<string>();

  get hasVariants(): boolean {
    return this.normalizedGroups.length > 0 || !!this.fallbackColour || !!this.visibleFallbackSize;
  }

  get normalizedGroups(): VariantOptionGroup[] {
    if (this.optionGroups.length > 0) {
      return this.optionGroups;
    }

    const groups: VariantOptionGroup[] = [];
    if (this.colours.length > 0) {
      groups.push({
        key: 'colour',
        label: 'itemDetail.colour',
        options: this.colours.map(value => ({ value }))
      });
    }

    if (this.sizes.length > 0) {
      groups.push({
        key: 'size',
        label: 'itemDetail.size',
        options: this.sizes.map(value => ({ value }))
      });
    }

    return groups;
  }

  isActive(groupKey: string, value: string): boolean {
    if (groupKey === 'colour') {
      return this.selectedColour === value;
    }

    if (groupKey === 'size') {
      return this.selectedSize === value;
    }

    return this.selectedOptions[groupKey] === value;
  }

  onSelect(groupKey: string, value: string): void {
    this.optionSelected.emit({ groupKey, value });

    if (groupKey === 'colour') {
      this.colourSelected.emit(value);
      return;
    }

    if (groupKey === 'size') {
      this.sizeSelected.emit(value);
    }
  }

  get visibleFallbackSize(): string | null {
    return this.fallbackSize && this.fallbackSize.toLowerCase() !== 'default' ? this.fallbackSize : null;
  }
}
