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 { ExpenseCategory } from '../../../models/expense-category.model';
import { ExpenseService } from '../../../services/expense.service';
import { FormFieldComponent } from '../../../shared/components/form-field/form-field.component';

@Component({
  selector: 'app-expense-category-modal',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, FormFieldComponent],
  templateUrl: './expense-category-modal.page.html',
  styleUrls: ['./expense-category-modal.page.scss']
})
export class ExpenseCategoryModalPage implements OnInit {
  form: FormGroup;
  isEditMode = false;
  saving = false;
  errorMessage = '';

  constructor(
    private fb: FormBuilder,
    private expenseService: ExpenseService,
    public dialogRef: MatDialogRef<ExpenseCategoryModalPage>,
    @Inject(MAT_DIALOG_DATA) public data: ExpenseCategory | null
  ) {
    this.form = this.fb.group({
      name: ['', [Validators.required, Validators.maxLength(80)]],
      description: ['', Validators.maxLength(250)]
    });
  }

  ngOnInit(): void {
    if (!this.data) {
      return;
    }

    this.isEditMode = true;
    this.form.patchValue({
      name: this.data.name,
      description: this.data.description ?? ''
    });
  }

  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 payload: ExpenseCategory = {
      name: this.form.value.name,
      description: this.form.value.description || null
    };

    const request$ = this.isEditMode && this.data?.id
      ? this.expenseService.updateCategory(this.data.id, payload)
      : this.expenseService.createCategory(payload);

    request$.subscribe({
      next: () => {
        this.saving = false;
        this.dialogRef.close({
          saved: true,
          message: this.isEditMode
            ? 'Categoria actualizada correctamente.'
            : 'Categoria creada correctamente.'
        });
      },
      error: () => {
        this.saving = false;
        this.errorMessage = this.isEditMode
          ? 'No se pudo actualizar la categoria.'
          : 'No se pudo crear la categoria.';
      }
    });
  }
}
