import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
} from '@angular/core';
import { ButtonComponent, TextButtonComponent } from '@isa/ui/buttons';
import {
  CrmTabMetadataService,
  PrimaryCustomerCardResource,
  SelectedCustomerResource,
} from '@isa/crm/data-access';
import { SkeletonLoaderDirective } from '@isa/ui/skeleton-loader';
import {
  CheckoutMetadataService,
  SelectedRewardShoppingCartResource,
} from '@isa/checkout/data-access';
import { RouterLink } from '@angular/router';
import { TabService, getNextTabNameHelper } from '@isa/core/tabs';
import { formatName } from '@isa/utils/format-name';
import { DomainCheckoutService } from '@domain/checkout';

@Component({
  selector: 'reward-customer-card',
  templateUrl: './reward-customer-card.component.html',
  styleUrl: './reward-customer-card.component.css',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    RouterLink,
    TextButtonComponent,
    ButtonComponent,
    SkeletonLoaderDirective,
  ],
})
export class RewardCustomerCardComponent {
  #crmTabMetadataService = inject(CrmTabMetadataService);
  #checkoutMetadataService = inject(CheckoutMetadataService);
  #domainCheckoutService = inject(DomainCheckoutService);
  #tabService = inject(TabService);
  #customerResource = inject(SelectedCustomerResource).resource;
  #shoppingCartResource = inject(SelectedRewardShoppingCartResource).resource;
  #primaryCustomerCardResource = inject(PrimaryCustomerCardResource);

  readonly customerValue = this.#customerResource.value.asReadonly();

  readonly primaryCustomerCardValue =
    this.#primaryCustomerCardResource.primaryCustomerCard;

  primaryBonusCardPoints = computed(
    () => this.primaryCustomerCardValue()?.totalPoints ?? 0,
  );

  readonly shoppingCartResponseValue =
    this.#shoppingCartResource.value.asReadonly();
  readonly shoppingCartResponseFetching = this.#shoppingCartResource.isLoading;

  cartItemsLength = computed(
    () => this.shoppingCartResponseValue()?.items?.length ?? 0,
  );

  customerName = computed(() => {
    const customer = this.customerValue();
    return formatName({
      firstName: customer?.firstName,
      lastName: customer?.lastName,
      organisationName: customer?.organisation?.name,
    });
  });

  resetCustomerAndRewardCart() {
    const tabId = this.#tabService.activatedTabId()!;

    // Clear all customer-related checkout data
    this.#clearCheckoutData(tabId);

    // Clear all customer-related metadata
    this.#clearCustomerMetadata(tabId);

    // Clear reward shopping cart ID from metadata
    this.#checkoutMetadataService.setRewardShoppingCartId(tabId, undefined);

    // Rename tab to "Vorgang X"
    const tabName = getNextTabNameHelper(this.#tabService.entityMap());
    this.#tabService.patchTab(tabId, { name: tabName });
  }

  /**
   * Clears all checkout data set by the continue() flow (customer, buyer, payer, shipping address, notification channels).
   * This is the reverse operation of what happens in details-main-view.component.ts continue().
   */
  #clearCheckoutData(tabId: number): void {
    // Reset customer (reverse of _setCustomer)
    this.#domainCheckoutService.setCustomer({
      processId: tabId,
      customerDto: null as any,
    });

    // Reset buyer (reverse of _setBuyer)
    this.#domainCheckoutService.setBuyer({
      processId: tabId,
      buyer: null as any,
    });

    // Reset payer (reverse of _setPayer)
    this.#domainCheckoutService.setPayer({
      processId: tabId,
      payer: null as any,
    });

    // Reset shipping address (reverse of _setShippingAddress)
    this.#domainCheckoutService.setShippingAddress({
      processId: tabId,
      shippingAddress: null as any,
    });

    // Reset notification channels (reverse of _updateNotifcationChannelsAsync)
    this.#domainCheckoutService.setNotificationChannels({
      processId: tabId,
      notificationChannels: 0,
    });
  }

  /**
   * Clears all customer-related metadata from the tab (customer ID, payer ID, shipping address ID).
   * This is the reverse operation of what happens in details-main-view.component.ts continue().
   */
  #clearCustomerMetadata(tabId: number): void {
    // Clear customer ID from metadata (reverse of _setSelectedCustomerIdInTab)
    this.#crmTabMetadataService.setSelectedCustomerId(tabId, undefined);

    // Clear payer ID from metadata
    this.#crmTabMetadataService.setSelectedPayerId(tabId, undefined);

    // Clear shipping address ID from metadata
    this.#crmTabMetadataService.setSelectedShippingAddressId(tabId, undefined);
  }
}
