import {
  Component,
  ChangeDetectionStrategy,
  inject,
  computed,
  effect,
  ElementRef,
  OnDestroy,
} from '@angular/core';
import { CustomerSearchStore } from '../store';
import { ActivatedRoute, Router } from '@angular/router';
import { map } from 'rxjs/operators';
import { TabService } from '@isa/core/tabs';
import { CustomerSearchNavigation } from '@shared/services/navigation';
import { AsyncPipe } from '@angular/common';
import { CustomerMenuComponent } from '../../components/customer-menu';
import { CustomerLoyaltyCardsComponent } from '@isa/crm/feature/customer-loyalty-cards';
import { CrmFeatureCustomerCardTransactionsComponent } from '@isa/crm/feature/customer-card-transactions';
import { toSignal } from '@angular/core/rxjs-interop';
import {
  CustomerBonusCardsResource,
  CustomerCardTransactionsResource,
} from '@isa/crm/data-access';
import { CrmFeatureCustomerBookingComponent } from '@isa/crm/feature/customer-booking';
import { CrmFeatureCustomerBonRedemptionComponent } from '@isa/crm/feature/customer-bon-redemption';
import { ScrollTopButtonComponent } from '@isa/utils/scroll-position';

@Component({
  selector: 'page-customer-kundenkarte-main-view',
  templateUrl: 'kundenkarte-main-view.component.html',
  styleUrls: ['kundenkarte-main-view.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'page-customer-kundenkarte-main-view' },
  imports: [
    CustomerMenuComponent,
    AsyncPipe,
    CustomerLoyaltyCardsComponent,
    CrmFeatureCustomerCardTransactionsComponent,
    CrmFeatureCustomerBookingComponent,
    CrmFeatureCustomerBonRedemptionComponent,
    ScrollTopButtonComponent,
  ],
  providers: [CustomerBonusCardsResource, CustomerCardTransactionsResource],
})
export class KundenkarteMainViewComponent implements OnDestroy {
  #reloadTimeoutId?: ReturnType<typeof setTimeout>;

  private _store = inject(CustomerSearchStore);
  private _activatedRoute = inject(ActivatedRoute);
  #bonusCardsResource = inject(CustomerBonusCardsResource);
  #cardTransactionsResource = inject(CustomerCardTransactionsResource);
  elementRef = inject(ElementRef);
  #router = inject(Router);
  #tabService = inject(TabService);
  #customerNavigationService = inject(CustomerSearchNavigation);

  /**
   * Returns the native DOM element of this component
   */
  get hostElement() {
    return this.elementRef.nativeElement;
  }

  customerId$ = this._activatedRoute.params.pipe(
    map((params) => params.customerId),
  );

  processId$ = this._store.processId$;

  /**
   * Convert customerId observable to signal for reactive usage
   */
  readonly customerId = toSignal(this.customerId$);

  /**
   * Get the first active card code
   */
  readonly firstActiveCardCode = computed(() => {
    const cards = this.#bonusCardsResource.resource.value();
    const firstActiveCard = cards?.find((card) => card.isActive);
    return firstActiveCard?.code;
  });

  constructor() {
    // Load bonus cards when customerId changes
    effect(() => {
      const customerId = this.customerId();
      if (customerId) {
        this.#bonusCardsResource.params({ customerId: Number(customerId) });
      }
    });
  }

  /**
   * Reloads both card transactions and bonus cards resources after a 500ms delay.
   * Only triggers reload if the resource is not currently loading to prevent concurrent requests.
   */
  reloadCardTransactionsAndCards() {
    this.#reloadTimeoutId = setTimeout(() => {
      if (!this.#cardTransactionsResource.resource.isLoading()) {
        this.#cardTransactionsResource.resource.reload();
      }

      if (!this.#bonusCardsResource.resource.isLoading()) {
        this.#bonusCardsResource.resource.reload();
      }
    }, 500);
  }

  /**
   * Handle navigation to Prämienshop with proper customer selection.
   * Uses autoTriggerContinueFn pattern to auto-select customer via details view.
   */
  async onNavigateToPraemienshop(): Promise<void> {
    const tabId = this._store.processId;
    const customerId = this.customerId();

    if (!customerId || !tabId) {
      return;
    }

    // Preserve context for auto-triggering continue() in details view
    this.#tabService.patchTabMetadata(tabId, {
      'select-customer': {
        returnUrl: `/${tabId}/reward`,
        autoTriggerContinueFn: true,
      },
    });

    // Navigate to customer details - will auto-trigger continue()
    await this.#router.navigate(
      this.#customerNavigationService.detailsRoute({
        processId: tabId,
        customerId: Number(customerId),
      }).path,
    );
  }

  ngOnDestroy(): void {
    if (this.#reloadTimeoutId) {
      clearTimeout(this.#reloadTimeoutId);
    }
  }
}
