import { ChangeDetectionStrategy, Component, computed, effect, input, output, signal } from '@angular/core';

import { ButtonComponent } from '../../../../../../shared/components/button/button.component';
import { IconButtonComponent } from '../../../../../../shared/components/icon-button/icon-button.component';
import { InputComponent } from '../../../../../../shared/components/input/input.component';
import { TransferAccount, TransferField } from '../../checkout-page.models';

@Component({
  selector: 'app-transfer-payment-content',
  standalone: true,
  imports: [ButtonComponent, IconButtonComponent, InputComponent],
  templateUrl: './transfer-payment-content.component.html',
  styleUrl: './transfer-payment-content.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TransferPaymentContentComponent {
  readonly transferAccount = input<TransferAccount | null>(null);
  readonly copiedTransferField = input<TransferField | null>(null);
  readonly isLoading = input(false);
  readonly requestError = input<string | null>(null);
  readonly initialPayerDni = input('');

  readonly copyTransferValue = output<{ field: TransferField; value: string }>();
  readonly requestTransferData = output<string>();

  protected readonly payerDni = signal('');
  protected readonly submitted = signal(false);
  protected readonly payerDniError = computed(() => {
    if (!this.submitted()) return null;

    const value = String(this.payerDni()).trim();
    if (!value) return 'Ingresá el DNI de la persona que realizará la transferencia.';
    if (!/^\d+$/.test(value)) return 'El DNI solo puede contener números.';
    if (!/^\d{7,8}$/.test(value)) return 'El DNI debe tener 7 u 8 dígitos.';

    return null;
  });

  constructor() {
    effect(() => {
      const initialDni = this.initialPayerDni();
      if (initialDni && !this.payerDni()) this.payerDni.set(initialDni);
    });
  }

  protected submitPayerDni(): void {
    this.submitted.set(true);
    if (this.payerDniError()) return;

    this.requestTransferData.emit(String(this.payerDni()).trim());
  }

  protected requestCopy(field: TransferField, value: string): void {
    this.copyTransferValue.emit({ field, value });
  }
}
