import {
  ChangeDetectionStrategy,
  Component,
  inject,
  output,
} from '@angular/core';
import { Validators } from '@angular/forms';
import { logger } from '@isa/core/logging';
import {
  CustomerBonusCardsResource,
  CustomerCardsFacade,
} from '@isa/crm/data-access';
import { TextButtonComponent } from '@isa/ui/buttons';
import { injectFeedbackDialog, injectTextInputDialog } from '@isa/ui/dialog';
import { firstValueFrom } from 'rxjs';

@Component({
  selector: 'crm-add-customer-card',
  templateUrl: './add-customer-card.component.html',
  styleUrl: './add-customer-card.component.css',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [TextButtonComponent],
})
export class AddCustomerCardComponent {
  #logger = logger(() => ({
    component: 'AddCustomerCardComponent',
  }));

  #customerCardsFacade = inject(CustomerCardsFacade);
  #bonusCardsResource = inject(CustomerBonusCardsResource);

  #textDialog = injectTextInputDialog();
  #feedbackDialog = injectFeedbackDialog();

  /**
   * Event emitted when a card has been successfully added.
   * Parent should reload cards and transactions.
   */
  readonly cardAdded = output<void>();

  async addCardDialog() {
    this.#logger.debug('Opening add card dialog');
    const dialogRef = this.#textDialog({
      title: 'Karte hinzufügen',
      data: {
        message:
          'Scannen Sie die Karte, die Sie dem Kundenkonto hinzufügen möchten oder geben Sie den 8-stelligen Kartencode ein.',
        inputLabel: 'Kartencode eingeben',
        confirmText: 'Hinzufügen',
        inputValidation: [
          {
            errorKey: 'required',
            inputValidator: Validators.required,
            errorText: 'Bitte geben Sie einen gültigen Kartencode ein',
          },
        ],
        onConfirm: async (cardCode: string) => {
          await this.addCard(cardCode);
        },
      },
      width: '30rem',
    });

    const dialogResult = await firstValueFrom(dialogRef.closed);

    if (dialogResult?.inputValue) {
      this.feedback();
      this.cardAdded.emit();
    }
  }

  feedback() {
    this.#feedbackDialog({
      data: {
        message: 'Karte wurde hinzugefügt',
      },
    });
  }

  async addCard(cardCode: string) {
    this.#logger.info('Adding customer card', () => ({ cardCode }));
    const customerId = this.#bonusCardsResource.customerId();

    if (!customerId) {
      this.#logger.warn('Cannot add card: customerId not available');
      return;
    }

    await this.#customerCardsFacade.addCard({
      customerId,
      loyaltyCardValues: {
        cardCode,
      },
    });
    this.#logger.info('Adding customer card complete', () => ({ cardCode }));
  }
}
