import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { GridModule } from '@progress/kendo-angular-grid';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { DialogsModule } from '@progress/kendo-angular-dialog';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { MonthlyStatementApiService } from '../../services/monthly-statement-api.service';
import { MonthlyStatementDto } from '../../models/expense.model';

@Component({
  selector: 'app-monthly-statement-page',
  standalone: true,
  imports: [CommonModule, FormsModule, GridModule, ButtonsModule, DialogsModule, InputsModule],
  templateUrl: './monthly-statement-page.component.html',
  styleUrls: ['./monthly-statement-page.component.scss'],
})
export class MonthlyStatementPageComponent implements OnInit {
  rows: MonthlyStatementDto[] = [];
  loading = false;
  yearFilter: number | null = null;

  dialogOpen = false;
  editing: MonthlyStatementDto | null = null;
  form = {
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    openingBalance: 0,
    totalOtherIncome: 0,
    bankStatementBalance: 0,
    notes: '',
  };
  preview: MonthlyStatementDto | null = null;

  constructor(private api: MonthlyStatementApiService) {}

  ngOnInit(): void { this.load(); }

  load(): void {
    this.loading = true;
    this.api.getAll(this.yearFilter ?? undefined).subscribe({
      next: r => { this.rows = r; this.loading = false; },
      error: () => { this.loading = false; },
    });
  }

  openNew(): void {
    this.editing = null;
    this.preview = null;
    this.form = {
      year: new Date().getFullYear(),
      month: new Date().getMonth() + 1,
      openingBalance: 0,
      totalOtherIncome: 0,
      bankStatementBalance: 0,
      notes: '',
    };
    this.dialogOpen = true;
  }

  openEdit(row: MonthlyStatementDto): void {
    this.editing = row;
    this.preview = row;
    this.form = {
      year: row.year,
      month: row.month,
      openingBalance: row.openingBalance,
      totalOtherIncome: row.totalOtherIncome,
      bankStatementBalance: row.bankStatementBalance,
      notes: row.notes ?? '',
    };
    this.dialogOpen = true;
  }

  save(): void {
    const done = () => { this.dialogOpen = false; this.load(); };
    if (this.editing == null) {
      this.api.create({
        year: this.form.year,
        month: this.form.month,
        openingBalance: this.form.openingBalance,
        totalOtherIncome: this.form.totalOtherIncome,
        bankStatementBalance: this.form.bankStatementBalance,
        notes: this.form.notes || null,
      }).subscribe({
        next: created => this.api.getById(created.id).subscribe(s => { this.preview = s; done(); }),
        error: err => alert(err?.error?.message ?? 'Create failed (a statement for that month may already exist).'),
      });
    } else {
      this.api.update(this.editing.id, {
        openingBalance: this.form.openingBalance,
        totalOtherIncome: this.form.totalOtherIncome,
        bankStatementBalance: this.form.bankStatementBalance,
        notes: this.form.notes || null,
      }).subscribe(done);
    }
  }

  finalize(row: MonthlyStatementDto): void {
    if (!confirm(`Finalize ${row.year}-${String(row.month).padStart(2, '0')}? This locks the statement.`)) return;
    this.api.finalize(row.id).subscribe(() => this.load());
  }
}
