import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { GridModule, PageChangeEvent } from '@progress/kendo-angular-grid';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { DropDownsModule } from '@progress/kendo-angular-dropdowns';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { DialogsModule } from '@progress/kendo-angular-dialog';
import { CHECK_STATUS_OPTIONS } from '../../../../shared/i18n/option-lists';
import { DisbursementApiService, CheckRegisterQuery } from '../../services/disbursement-api.service';
import { ReceiptSignDialogComponent, ReceiptSignResult } from '../../components/receipt-sign-dialog/receipt-sign-dialog.component';
import { CheckListItemDto, CheckDetailDto } from '../../models/disbursement.model';

@Component({
  selector: 'app-check-register-page',
  standalone: true,
  imports: [
    CommonModule, FormsModule, GridModule, ButtonsModule, DropDownsModule,
    InputsModule, DialogsModule, ReceiptSignDialogComponent,
  ],
  templateUrl: './check-register-page.component.html',
  styleUrls: ['./check-register-page.component.scss'],
})
export class CheckRegisterPageComponent implements OnInit {
  rows: CheckListItemDto[] = [];
  total = 0;
  page = 1;
  pageSize = 20;
  loading = false;

  readonly statuses = CHECK_STATUS_OPTIONS;
  filter: CheckRegisterQuery = {};

  detail: CheckDetailDto | null = null;
  signRow: CheckListItemDto | null = null;
  voidRow: CheckListItemDto | null = null;
  voidReason = '';

  constructor(private api: DisbursementApiService) {}

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

  load(): void {
    this.loading = true;
    this.api.getRegister({ ...this.filter, page: this.page, pageSize: this.pageSize }).subscribe({
      next: r => { this.rows = r.items; this.total = r.totalCount; this.loading = false; },
      error: () => (this.loading = false),
    });
  }

  get skip(): number { return (this.page - 1) * this.pageSize; }
  get totalPages(): number { return Math.max(1, Math.ceil(this.total / this.pageSize)); }
  applyFilter(): void { this.page = 1; this.load(); }
  onPageChange(e: PageChangeEvent): void { this.page = Math.floor(e.skip / this.pageSize) + 1; this.load(); }

  prevPage(): void {
    if (this.page > 1) {
      this.page--;
      this.load();
    }
  }

  nextPage(): void {
    if (this.page < this.totalPages) {
      this.page++;
      this.load();
    }
  }

  view(row: CheckListItemDto): void {
    this.api.getCheck(row.id).subscribe(d => (this.detail = d));
  }

  print(row: CheckListItemDto): void {
    this.api.downloadCheckPdf(row.id).subscribe(blob => this.openBlob(blob));
  }

  viewSignature(row: CheckListItemDto): void {
    this.api.getSignature(row.id).subscribe(blob => this.openBlob(blob));
  }

  printReceipt(row: CheckListItemDto): void {
    this.api.downloadReceiptPdf(row.id).subscribe(blob => this.openBlob(blob));
  }

  openSign(row: CheckListItemDto): void { this.signRow = row; }

  onSign(result: ReceiptSignResult): void {
    if (!this.signRow) return;
    this.api.acknowledge(this.signRow.id, result.signature, result.signedName).subscribe({
      next: () => { this.signRow = null; this.load(); },
      error: () => {
        // Error message is shown globally by httpErrorInterceptor; keep the dialog open to retry.
      },
    });
  }

  openVoid(row: CheckListItemDto): void { this.voidRow = row; this.voidReason = ''; }

  confirmVoid(): void {
    if (!this.voidRow) return;
    this.api.voidCheck(this.voidRow.id, this.voidReason || null).subscribe({
      next: () => { this.voidRow = null; this.load(); },
      error: () => {
        // Error message is shown globally by httpErrorInterceptor; keep the dialog open to retry.
      },
    });
  }

  canSign(row: CheckListItemDto): boolean { return row.status === 'Issued' && !row.signed; }
  canVoid(row: CheckListItemDto): boolean { return row.status === 'Issued'; }

  statusClass(status: string): string {
    return ({ Issued: 'badge-approved', Voided: 'badge-rejected' } as Record<string, string>)[status] ?? '';
  }

  private openBlob(blob: Blob): void {
    const url = URL.createObjectURL(blob);
    window.open(url, '_blank');
    setTimeout(() => URL.revokeObjectURL(url), 60_000);
  }
}
