import {
  ChangeDetectionStrategy,
  Component,
  computed,
  input,
} from '@angular/core';
import { Product as CatProduct } from '@isa/catalogue/data-access';
import { Product as CheckoutProduct } from '@isa/checkout/data-access';
import { ProductFormatComponent } from '@isa/shared/product-format';
import { DatePipe } from '@angular/common';
import { Loyalty } from '@isa/checkout/data-access';
import {
  ProductInfoComponent,
  ProductInfoItem,
} from './product-info.component';

export type ProductInfoRedemptionItem =
  | {
      product: Pick<
        CatProduct,
        | 'ean'
        | 'name'
        | 'contributors'
        | 'format'
        | 'formatDetail'
        | 'manufacturer'
        | 'publicationDate'
      >;
      redemptionPoints?: number;
    }
  | {
      product: Pick<
        CheckoutProduct,
        | 'ean'
        | 'name'
        | 'contributors'
        | 'format'
        | 'formatDetail'
        | 'manufacturer'
        | 'publicationDate'
      >;
      loyalty: Pick<Loyalty, 'value'>;
    };

@Component({
  selector: 'checkout-product-info-redemption',
  templateUrl: './product-info-redemption.component.html',
  styleUrls: ['./product-info-redemption.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  imports: [ProductInfoComponent, ProductFormatComponent, DatePipe],
  host: {
    '[class]': '[orientation()]',
  },
})
export class ProductInfoRedemptionComponent {
  item = input.required<ProductInfoRedemptionItem>();

  orientation = input<'horizontal' | 'vertical'>('vertical');

  points = computed(() => {
    const item = this.item();
    if ('redemptionPoints' in item) {
      return item.redemptionPoints ?? 0;
    }

    if ('loyalty' in item && item.loyalty) {
      return item.loyalty.value ?? 0;
    }

    return 0;
  });

  nameSize = computed(() => {
    return this.orientation() === 'horizontal' ? 'small' : 'medium';
  });

  baseItem = computed<ProductInfoItem>(() => {
    const item = this.item();
    return {
      ean: item.product.ean ?? '',
      name: item.product.name ?? '',
      contributors: item.product.contributors ?? '',
    };
  });
}
