import {
  ChangeDetectionStrategy,
  Component,
  computed,
  input,
  output,
  signal,
  OnInit,
  effect,
  untracked,
} from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { IconButtonComponent } from '../../../../../../shared/components/icon-button/icon-button.component';
import { ButtonComponent } from '../../../../../../shared/components/button/button.component';
import { InputComponent } from '../../../../../../shared/components/input/input.component';
import {
  TransferAccount,
  TransferField,
  TransferValidationStatus,
} from '../../checkout-page.models';
import { PaymentVerificationErrorComponent } from '../payment-verification-error/payment-verification-error.component';

@Component({
  selector: 'app-checkout-payment-transfer',
  standalone: true,
  imports: [
    IconButtonComponent,
    ButtonComponent,
    InputComponent,
    ReactiveFormsModule,
    PaymentVerificationErrorComponent,
  ],
  templateUrl: './checkout-payment-transfer.component.html',
  styleUrl: './checkout-payment-transfer.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CheckoutPaymentTransferComponent implements OnInit {
  readonly transferAccount = input<TransferAccount | null>(null);
  readonly transferDni = input<string>('');
  readonly copiedTransferField = input<TransferField | null>(null);
  readonly validationStatus = input<TransferValidationStatus>('idle');
  readonly paymentAmount = input<number>(0);
  readonly whatsappUrl = input<string | null>(null);
  readonly verificationErrorTitle = input<string | null>(null);

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

  protected readonly dniControl = new FormControl('', {
    nonNullable: true,
    validators: [Validators.required, Validators.pattern(/^\d{7,8}$/)],
  });

  protected readonly isEditing = signal<boolean>(false);
  protected readonly isDniDisabled = computed(() => !!this.transferAccount() && !this.isEditing());

  ngOnInit(): void {
    const dni = this.transferDni();
    if (dni) {
      this.dniControl.setValue(dni);
    }
  }

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

  protected onSubmitDni(): void {
    if (this.dniControl.valid) {
      this.isEditing.set(false);
      this.submitDni.emit(this.dniControl.value);
    }
  }

  protected enableEditing(): void {
    this.isEditing.set(true);
  }
}
