import { ChangeDetectionStrategy, Component, input, output } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';

import { ButtonComponent } from '../../../../shared/components/button/button.component';
import { InputComponent } from '../../../../shared/components/input/input.component';
import { CheckoutForm } from './checkout-page.models';

@Component({
  selector: 'app-checkout-data-step',
  standalone: true,
  imports: [ReactiveFormsModule, InputComponent, ButtonComponent],
  templateUrl: './checkout-data-step.component.html',
  styleUrl: './checkout-data-step.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CheckoutDataStepComponent {
  readonly form = input.required<CheckoutForm>();
  readonly cancelStep = output<void>();
  readonly continueStep = output<void>();

  protected updateField(field: keyof CheckoutForm['controls'], value: string | number): void {
    this.form().controls[field].setValue(String(value));
  }

  protected showControlError(controlName: keyof CheckoutForm['controls']): boolean {
    const control = this.form().controls[controlName];
    return control.invalid && control.touched;
  }

  protected getControlError(controlName: keyof CheckoutForm['controls']): string | null {
    const control = this.form().controls[controlName];
    if (!this.showControlError(controlName)) return null;
    if (control.hasError('required')) return 'Este campo es obligatorio.';
    if (control.hasError('email')) return 'Ingresa un email valido.';
    return 'El valor ingresado no es valido.';
  }

  protected submit(): void {
    const form = this.form();
    if (form.invalid) {
      form.markAllAsTouched();
      return;
    }

    this.continueStep.emit();
  }
}
