import { NgOptimizedImage } from '@angular/common';
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';

import { ButtonComponent } from '../button/button.component';
import { TooltipComponent } from '../tooltip/tooltip.component';

@Component({
  selector: 'app-product-column-with-image',
  imports: [ButtonComponent, NgOptimizedImage, TooltipComponent],
  templateUrl: './product-column-with-image.component.html',
  styleUrl: './product-column-with-image.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProductColumnWithImageComponent {
  readonly imageUrl = input<string | null>(null);
  readonly title = input<string>('');
  readonly originalPrice = input<number>(0);
  readonly discount = input<number | null>(null);
  readonly transferPrice = input<number | null>(null);
  readonly buttonText = input<string>('Comprar');
  readonly imagePriority = input<boolean>(false);
  readonly unavailableMessage = input<string | null>(null);

  readonly buy = output<void>();

  protected onBuy(): void {
    if (this.unavailableMessage()) return;

    this.buy.emit();
  }

  readonly discountedPrice = computed(() => {
    const original = this.originalPrice();
    const discount = this.discount();

    return !discount || discount <= 0 ? original : original * (1 - discount / 100);
  });

  readonly computedTransferPrice = computed(() => {
    return this.transferPrice() ?? this.discountedPrice();
  });

  readonly formattedDiscountedPrice = computed(() => this.formatCurrency(this.discountedPrice()));
  readonly formattedOriginalPrice = computed(() => this.formatCurrency(this.originalPrice()));
  readonly formattedTransferPrice = computed(() =>
    this.formatCurrency(this.computedTransferPrice()),
  );

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