import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  signal,
} from '@angular/core';
import { ButtonComponent } from '@isa/ui/buttons';
import {
  CheckoutMetadataService,
  SelectedRewardShoppingCartResource,
  calculateTotalLoyaltyPoints,
} from '@isa/checkout/data-access';
import {
  SelectedCustomerResource,
  CrmTabMetadataService,
  PrimaryCustomerCardResource,
} from '@isa/crm/data-access';
import { injectTabId } from '@isa/core/tabs';
import { logger } from '@isa/core/logging';
import { CheckoutCompletionOrchestratorService } from '../services';
import { Router } from '@angular/router';
import { injectFeedbackErrorDialog } from '@isa/ui/dialog';

@Component({
  selector: 'checkout-complete-order-button',
  templateUrl: './complete-order-button.component.html',
  styleUrls: ['./complete-order-button.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ButtonComponent],
  providers: [CheckoutCompletionOrchestratorService],
})
export class CompleteOrderButtonComponent {
  #logger = logger(() => ({
    component: 'CompleteOrderButtonComponent',
    tabId: this.#tabId(),
  }));
  #tabId = injectTabId();
  #errorFeedbackDialog = injectFeedbackErrorDialog();
  #tabMetadata = inject(CrmTabMetadataService);
  #checkoutMetadata = inject(CheckoutMetadataService);

  #orchestrator = inject(CheckoutCompletionOrchestratorService);
  #customerResource = inject(SelectedCustomerResource);
  #shoppingCartResource = inject(SelectedRewardShoppingCartResource).resource;
  #primaryCustomerCardResource = inject(PrimaryCustomerCardResource);

  #router = inject(Router);

  isBusy = signal(false);
  isCompleted = signal(false);

  primaryBonusCardPoints = computed(
    () =>
      this.#primaryCustomerCardResource.primaryCustomerCard()?.totalPoints ?? 0,
  );

  totalPointsRequired = computed(() => {
    const cart = this.#shoppingCartResource.value();
    return calculateTotalLoyaltyPoints(cart?.items);
  });

  hasItemsInCart = computed(() => {
    const cart = this.#shoppingCartResource.value();
    return cart && cart?.items?.length > 0;
  });

  hasInsufficientPoints = computed(() => {
    return this.primaryBonusCardPoints() < this.totalPointsRequired();
  });

  shippingAddress = computed(() => {
    const tabId = this.#tabId();
    const sa = tabId
      ? this.#tabMetadata.selectedShippingAddressId(tabId)
      : null;

    if (!sa) {
      return null;
    }

    const shippingAddresses =
      this.#customerResource.resource.value()?.shippingAddresses;

    return shippingAddresses?.find((a) => a.id === sa)?.data ?? null;
  });

  payer = computed(() => {
    const tabId = this.#tabId();
    const payerId = tabId ? this.#tabMetadata.selectedPayerId(tabId) : null;

    if (!payerId) {
      return null;
    }

    const payers = this.#customerResource.resource
      .value()
      ?.payers?.map((p) => p.payer?.data);

    return payers?.find((p) => p?.id === payerId) ?? null;
  });

  isLoading = computed(() => {
    return this.#customerResource.resource.isLoading() || this.isBusy();
  });

  isDisabled = computed(() => {
    return (
      this.isBusy() ||
      this.isCompleted() ||
      this.isLoading() ||
      !this.hasItemsInCart() ||
      this.hasInsufficientPoints()
    );
  });

  shoppingCartId = computed(() => {
    const tabId = this.#tabId();
    return tabId ? this.#checkoutMetadata.getRewardShoppingCartId(tabId) : null;
  });

  async complete() {
    if (this.isDisabled()) {
      return;
    }

    this.isBusy.set(true);

    try {
      const shoppingCartId = this.shoppingCartId();
      if (!shoppingCartId) {
        throw new Error('Missing shopping cart ID');
      }

      const customer = this.#customerResource.resource.value();
      if (!customer) {
        throw new Error('Missing customer data');
      }

      // Complete order using orchestrator with CRM data
      const orders = await this.#orchestrator.completeCheckoutAndCreateOrders(
        {
          shoppingCartId,
          crmCustomer: customer,
          crmShippingAddress: this.shippingAddress() ?? undefined,
          crmPayer: this.payer() ?? undefined,
          notificationChannels: customer.notificationChannels ?? 0,
        },
        this.#tabId() ?? undefined,
      );

      await this.#router.navigate([
        `/${this.#tabId()}`,
        'reward',
        'order-confirmation',
        orders.map((o) => o.id).join(','),
      ]);

      this.isCompleted.set(true);
      this.#logger.info('Order completed successfully', () => ({ orders }));
    } catch (error: any) {
      this.#errorFeedbackDialog({
        data: {
          errorMessage: 'Bestellung konnte nicht abgeschlossen werden.',
        },
      });
      this.#logger.error('Error completing order', error);
    } finally {
      this.isBusy.set(false);
    }
  }
}
