import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { DialogsModule } from '@progress/kendo-angular-dialog';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { DateInputsModule } from '@progress/kendo-angular-dateinputs';
import { GridModule } from '@progress/kendo-angular-grid';
import { PayeeGroupDto, IssueChecksRequest, PayeeCheckInstruction } from '../../models/disbursement.model';

interface PayeeForm {
  group: PayeeGroupDto;
  payeeName: string;
  address: string;
  city: string;
  state: string;
  zip: string;
  checkNumber: string;
  defaultCheckNumber: string;
  memo: string;
}

@Component({
  selector: 'app-issue-check-dialog',
  standalone: true,
  imports: [CommonModule, FormsModule, DialogsModule, ButtonsModule, InputsModule, DateInputsModule, GridModule],
  templateUrl: './issue-check-dialog.component.html',
})
export class IssueCheckDialogComponent implements OnInit {
  /** The payee groups the user selected to pay. */
  @Input() groups: PayeeGroupDto[] = [];
  /** Next sequential check number from the church profile, used to prefill. */
  @Input() nextCheckNumber = 1001;

  @Output() save = new EventEmitter<IssueChecksRequest>();
  @Output() cancel = new EventEmitter<void>();

  checkDate = new Date();
  forms: PayeeForm[] = [];

  ngOnInit(): void {
    let n = this.nextCheckNumber;
    this.forms = this.groups.map(g => {
      const cn = String(n++);
      return {
        group: g,
        payeeName: g.payeeName,
        address: g.address ?? '',
        city: g.city ?? '',
        state: g.state ?? '',
        zip: g.zip ?? '',
        checkNumber: cn,
        defaultCheckNumber: cn,
        memo: '',
      };
    });
  }

  confirm(): void {
    const d = this.checkDate;
    const checkDate = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;

    const payees: PayeeCheckInstruction[] = this.forms.map(f => ({
      payeeType: f.group.payeeType,
      memberId: f.group.memberId,
      vendorKey: f.group.vendorKey,
      payeeName: f.payeeName.trim(),
      address: f.address.trim() || null,
      city: f.city.trim() || null,
      state: f.state.trim() || null,
      zip: f.zip.trim() || null,
      // Only send an override when the user changed the prefilled sequential number,
      // so the server's auto-allocation (and counter consumption) stays in sync.
      checkNumberOverride: f.checkNumber.trim() !== f.defaultCheckNumber ? f.checkNumber.trim() : null,
      memo: f.memo.trim() || null,
      expenseIds: f.group.lines.map(l => l.expenseId),
    }));

    this.save.emit({ checkDate, payees });
  }

  onClose(): void { this.cancel.emit(); }
}
