import {
  ChangeDetectionStrategy,
  Component,
  inject,
  input,
  output,
  signal,
} from '@angular/core';
import { logger } from '@isa/core/logging';
import {
  CustomerBonusCardsResource,
  CustomerCardsFacade,
} from '@isa/crm/data-access';
import { TextButtonComponent } from '@isa/ui/buttons';
import {
  injectFeedbackDialog,
  injectFeedbackErrorDialog,
} from '@isa/ui/dialog';

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

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

  #feedbackDialog = injectFeedbackDialog();
  #errorFeedbackDialog = injectFeedbackErrorDialog();

  readonly isActive = input.required<boolean>();
  readonly cardCode = input.required<string>();

  readonly #customerId = this.#bonusCardsResource.customerId;

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

  loading = signal(false);

  async lockCard() {
    const cardCode = this.cardCode();
    try {
      this.loading.set(true);
      await this.#customerCardsFacade.lockCard({
        cardCode,
      });
      this.#feedbackDialog({
        data: {
          message: 'Karte gesperrt',
        },
      });
      this.cardLocked.emit();
    } catch (error: unknown) {
      this.#logger.error('Error locking card', error as Error, () => ({
        cardCode,
      }));
      this.#errorFeedbackDialog({
        data: {
          error,
        },
      });
    } finally {
      this.loading.set(false);
    }
  }

  async unlockCard() {
    const customerId = this.#customerId();
    const cardCode = this.cardCode();

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

    try {
      this.loading.set(true);
      await this.#customerCardsFacade.unlockCard({
        cardCode,
        customerId,
      });
      this.#feedbackDialog({
        data: {
          message: 'Karte entsperrt',
        },
      });
      this.cardLocked.emit();
    } catch (error: unknown) {
      this.#logger.error('Error unlocking card', error as Error, () => ({
        cardCode,
      }));
      this.#errorFeedbackDialog({
        data: {
          error,
        },
      });
    } finally {
      this.loading.set(false);
    }
  }
}
