import {
  ChangeDetectionStrategy,
  Component,
  computed,
  effect,
  input,
  output,
  model,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ButtonComponent } from '../button/button.component';
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';

export interface Variant {
  label: string;
  value: any;
}

@Component({
  selector: 'app-product-row-card',
  standalone: true,
  imports: [ButtonComponent, QuantitySelectorComponent, FormsModule],
  templateUrl: './product-row-card.component.html',
  styleUrl: './product-row-card.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProductRowCardComponent {
  // Configurable inputs
  readonly title = input<string>('');
  readonly description = input<string>('');
  readonly price = input<number>(0);
  readonly variants = input<Variant[]>([]);

  // Internal state models
  readonly quantity = model<number>(1);
  readonly selectedVariant = model<any>(null);

  // Interactive events
  readonly buy = output<{ quantity: number; variant: any }>();
  readonly addToCart = output<{ quantity: number; variant: any }>();

  constructor() {
    effect(() => {
      const variants = this.variants();
      const selectedVariant = this.selectedVariant();

      if (
        variants.length > 0 &&
        !variants.some((variant) => Object.is(variant.value, selectedVariant))
      ) {
        this.selectedVariant.set(variants[0].value);
      }
    });
  }

  // Formatted string for price: "$ 10.000"
  readonly formattedPrice = computed(() => {
    return this.formatCurrency(this.price());
  });

  protected onAddToCart(): void {
    this.addToCart.emit({
      quantity: this.quantity(),
      variant: this.selectedVariant(),
    });
  }

  protected onBuy(): void {
    this.buy.emit({
      quantity: this.quantity(),
      variant: this.selectedVariant(),
    });
  }

  /**
   * Helper method to format currency numbers to Argentine Pesos style "$ XX.XXX".
   */
  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(',')}`;
  }
}
