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';

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

@Component({
  selector: 'app-cart-item',
  standalone: true,
  imports: [QuantitySelectorComponent, IconButtonComponent],
  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 quantity = input<number>(1);

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

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

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

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

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

  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(',')}`;
  }
}
