import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
import { IconButtonComponent } from '../icon-button/icon-button.component';
import {
  VariantSelectorComponent,
  VariantSelectorVariant,
} from '../variant-selector/variant-selector.component';

export interface CartItemAttribute {
  label: string;
  value: string;
}

@Component({
  selector: 'app-cart-item',
  standalone: true,
  imports: [QuantitySelectorComponent, IconButtonComponent, VariantSelectorComponent],
  templateUrl: './cart-item.component.html',
  styleUrl: './cart-item.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CartItemComponent {
  readonly imageUrl = input<string | null>(null);
  readonly product = input<string>('');
  readonly originalPrice = input<number | null>(null);
  readonly discountedPrice = input<number>(0);
  readonly discountPercentage = input<number | null>(null);
  readonly attributes = input<CartItemAttribute[]>([]);
  readonly variants = input<VariantSelectorVariant[]>([]);
  readonly selectedVariant = input<unknown>(null);
  readonly quantity = input<number>(1);
  readonly readonly = input<boolean>(false);
  readonly quantityDisabled = input<boolean>(false);
  readonly variantDisabled = input<boolean>(false);
  readonly removeDisabled = input<boolean>(false);
  readonly allowDelete = input<boolean>(true);

  readonly quantityChange = output<number>();
  readonly remove = output<void>();
  readonly increase = output<void>();
  readonly decrease = output<void>();
  readonly variantChange = output<number>();

  protected readonly hasVariantSelectors = computed(() =>
    this.variants().some((variant) => Object.keys(variant.values).length > 0),
  );

  protected onQuantityChange(newQuantity: number): void {
    if (this.quantityDisabled()) return;
    this.quantityChange.emit(newQuantity);
  }

  protected onRemove(): void {
    this.remove.emit();
  }

  protected onIncrease(): void {
    this.increase.emit();
  }

  protected onDecrease(): void {
    this.decrease.emit();
  }

  protected onVariantChange(variant: unknown): void {
    if (!this.variantDisabled() && typeof variant === 'number') {
      this.variantChange.emit(variant);
    }
  }

  protected readonly formattedOriginalPrice = computed(() => {
    const price = this.originalPrice();
    return price === null ? null : this.formatCurrency(price);
  });

  protected readonly formattedDiscountedPrice = computed(() =>
    this.formatCurrency(this.discountedPrice()),
  );

  private formatCurrency(value: number): string {
    const rounded = Math.round(value);
    const parts = rounded.toString().split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, '.');
    return `$ ${parts.join(',')}`;
  }
}
