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 { DisbursementApiService } from '../../services/disbursement-api.service';
import { IssueCheckDialogComponent } from '../../components/issue-check-dialog/issue-check-dialog.component';
import { PayeeGroupDto, IssueChecksRequest } from '../../models/disbursement.model';
import { PageHeaderActionsDirective } from '../../../../shared/directives/page-header-actions.directive';

interface PayeeRow extends PayeeGroupDto { key: string; }

@Component({
  selector: 'app-disbursement-page',
  standalone: true,
  imports: [CommonModule, FormsModule, GridModule, ButtonsModule, IssueCheckDialogComponent, PageHeaderActionsDirective],
  templateUrl: './disbursement-page.component.html',
  styleUrls: ['./disbursement-page.component.scss'],
})
export class DisbursementPageComponent implements OnInit {
  rows: PayeeRow[] = [];
  selectedKeys: string[] = [];
  loading = false;
  nextCheckNumber = 1001;

  issueDialogGroups: PayeeGroupDto[] | null = null;

  constructor(private api: DisbursementApiService) {}

  ngOnInit(): void {
    this.api.getChurchProfile().subscribe(p => (this.nextCheckNumber = p.nextCheckNumber));
    this.load();
  }

  load(): void {
    this.loading = true;
    this.selectedKeys = [];
    this.api.getApprovedUnpaid().subscribe({
      next: groups => {
        this.rows = groups.map(g => ({ ...g, key: this.keyOf(g) }));
        this.loading = false;
      },
      error: () => (this.loading = false),
    });
  }

  private keyOf(g: PayeeGroupDto): string {
    return `${g.payeeType}:${g.payeeType === 'Member' ? g.memberId : g.vendorKey}`;
  }

  get selectedCount(): number { return this.selectedKeys.length; }

  openIssue(): void {
    const selected = this.rows.filter(r => this.selectedKeys.includes(r.key));
    if (selected.length === 0) return;
    this.issueDialogGroups = selected;
  }

  onIssue(req: IssueChecksRequest): void {
    this.api.issue(req).subscribe({
      next: result => {
        this.issueDialogGroups = null;
        result.created.forEach(c => this.openPdf(c.checkId));
        this.load();
      },
      error: () => {
        // Error message is shown globally by httpErrorInterceptor; keep the dialog open to retry.
      },
    });
  }

  private openPdf(checkId: number): void {
    this.api.downloadCheckPdf(checkId).subscribe(blob => {
      const url = URL.createObjectURL(blob);
      window.open(url, '_blank');
      setTimeout(() => URL.revokeObjectURL(url), 60_000);
    });
  }
}
