import { Component, computed, input } from '@angular/core';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { OrderItemGroup } from '@isa/checkout/data-access';
import { DisplayOrderItem } from '@isa/oms/data-access';
import {
  OrderDestinationComponent,
  ShippingAddress,
} from '@isa/shared/delivery';
import { logger } from '@isa/core/logging';

@Component({
  selector: 'checkout-display-order-destination-info',
  templateUrl: './display-order-destination-info.component.html',
  styleUrls: ['./display-order-destination-info.component.css'],
  imports: [OrderDestinationComponent],
})
export class DisplayOrderDestinationInfoComponent {
  #logger = logger({ component: 'DisplayOrderDestinationInfoComponent' });

  underline = input<boolean, unknown>(false, {
    transform: coerceBooleanProperty,
  });

  // Accept the parent DisplayOrder (required for branch info)
  order = input.required<OrderItemGroup>();

  // Optionally accept DisplayOrderItem (for potential future item-specific logic)
  item = input<DisplayOrderItem>();

  orderType = computed(() => {
    return this.order().orderType;
  });

  mappedBranch = computed(() => {
    const order = this.order();
    const branch = order.targetBranch;
    this.#logger.debug('Mapping branch from DisplayOrder', () => ({
      branchName: branch?.name,
      branchAddress: branch?.address,
    }));
    return branch
      ? {
          name: branch.name,
          address: branch.address,
        }
      : undefined;
  });

  mappedShippingAddress = computed<ShippingAddress | undefined>(() => {
    const order = this.order();
    const shippingAddress = order.shippingAddress;

    this.#logger.debug('Mapping shipping address from DisplayOrder', () => ({
      firstName: shippingAddress?.firstName,
      lastName: shippingAddress?.lastName,
      hasAddress: !!shippingAddress?.address,
    }));

    if (!shippingAddress) {
      return undefined;
    }

    return {
      firstName: shippingAddress.firstName,
      lastName: shippingAddress.lastName,
      address: shippingAddress.address,
    };
  });

  // DisplayOrder doesn't have estimatedDelivery
  estimatedDelivery = computed(() => null);
}
