import { CommonModule } from '@angular/common';
import { Component, Inject, OnInit } from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  ReactiveFormsModule,
  Validators
} from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';

import { ReceivablePayment, ReceivablePaymentMethod } from '../../../models/receivable-payment.model';
import { User } from '../../../models/user.model';
import { ReceivableService } from '../../../services/receivable.service';
import { FormFieldComponent } from '../../../shared/components/form-field/form-field.component';

interface ReceivablePaymentDialogData {
  receivableId: number;
  users: User[];
}

@Component({
  selector: 'app-receivable-payment-page',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, FormFieldComponent],
  templateUrl: './receivable-payment.page.html',
  styleUrls: ['./receivable-payment.page.scss']
})
export class ReceivablePaymentPage implements OnInit {
  form: FormGroup;
  saving = false;
  errorMessage = '';
  users: User[] = [];

  readonly paymentMethodOptions = [
    { label: 'Efectivo', value: 'CASH' },
    { label: 'Transferencia', value: 'TRANSFER' },
    { label: 'Tarjeta', value: 'CARD' },
    { label: 'Credito', value: 'CREDIT' },
    { label: 'Otro', value: 'OTHER' }
  ];

  constructor(
    private fb: FormBuilder,
    private receivableService: ReceivableService,
    public dialogRef: MatDialogRef<ReceivablePaymentPage>,
    @Inject(MAT_DIALOG_DATA) public data: ReceivablePaymentDialogData
  ) {
    this.form = this.fb.group({
      registeredByUserId: [null, Validators.required],
      amount: [null, [Validators.required, Validators.min(0.01)]],
      paymentDate: ['', Validators.required],
      paymentMethod: ['TRANSFER', Validators.required],
      reference: ['', Validators.maxLength(120)],
      notes: ['', Validators.maxLength(400)]
    });
  }

  ngOnInit(): void {
    this.users = this.data.users ?? [];

    if (this.users.length === 1) {
      this.form.patchValue({ registeredByUserId: this.users[0].id ?? null });
    }

    this.form.patchValue({
      paymentDate: new Date().toISOString().slice(0, 10)
    });
  }

  get userOptions() {
    return this.users.map(user => ({
      label: user.name,
      value: user.id
    }));
  }

  getSafeControl(name: string): FormControl {
    return (this.form.get(name) as FormControl) ?? new FormControl();
  }

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

    this.saving = true;
    this.errorMessage = '';

    const raw = this.form.getRawValue();
    const payload: ReceivablePayment = {
      registeredByUserId: Number(raw.registeredByUserId),
      amount: Number(raw.amount),
      paymentDate: new Date(raw.paymentDate).toISOString(),
      paymentMethod: raw.paymentMethod as ReceivablePaymentMethod,
      reference: raw.reference || null,
      notes: raw.notes || null
    };

    this.receivableService.registerPayment(this.data.receivableId, payload).subscribe({
      next: () => {
        this.saving = false;
        this.dialogRef.close({
          saved: true,
          message: 'Abono registrado correctamente.'
        });
      },
      error: () => {
        this.saving = false;
        this.errorMessage = 'No se pudo registrar el abono.';
      }
    });
  }
}
