import { Component, OnInit, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { GridModule, CellClickEvent } from '@progress/kendo-angular-grid';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { DialogsModule } from '@progress/kendo-angular-dialog';
import { DropDownsModule } from '@progress/kendo-angular-dropdowns';
import { ContextMenuModule, ContextMenuComponent, ContextMenuSelectEvent } from '@progress/kendo-angular-menu';
import { Form1099ReportApiService } from '../../../payee1099/services/form1099-report-api.service';
import {
  Form1099Summary, Form1099RecipientRow, Form1099RecipientDetail,
} from '../../../payee1099/models/payee1099.model';
import { PageHeaderActionsDirective } from '../../../../shared/directives/page-header-actions.directive';

@Component({
  selector: 'app-form1099-report-page',
  standalone: true,
  imports: [
    CommonModule, FormsModule, GridModule, ButtonsModule, DialogsModule,
    DropDownsModule, ContextMenuModule, PageHeaderActionsDirective,
  ],
  templateUrl: './form1099-report-page.component.html',
  styleUrls: ['./form1099-report-page.component.scss'],
})
export class Form1099ReportPageComponent implements OnInit {
  /** Recent years offered in the selector: current year and the prior four. */
  readonly years: number[] = [];
  taxYear: number = new Date().getFullYear();

  summary: Form1099Summary | null = null;
  loading = false;

  // Per-row "Copy B" action, surfaced through a right-click context menu (matches
  // the recipients page convention of putting row actions in a context menu).
  @ViewChild('rowMenu') rowMenu!: ContextMenuComponent;
  rowMenuItems: { text: string }[] = [];
  private contextRow: Form1099RecipientRow | null = null;

  detail: Form1099RecipientDetail | null = null;
  detailLoading = false;

  constructor(private api: Form1099ReportApiService) {
    const currentYear = new Date().getFullYear();
    for (let offset = 0; offset < 5; offset++) {
      this.years.push(currentYear - offset);
    }
  }

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

  load(): void {
    this.loading = true;
    this.api.getSummary(this.taxYear).subscribe({
      next: (summary) => {
        this.summary = summary;
        this.loading = false;
      },
      error: () => { this.loading = false; },
    });
  }

  // ── Row interaction: primary click opens the detail; right-click shows actions ──
  onCellClick(event: CellClickEvent): void {
    if (event.type === 'contextmenu') {
      event.originalEvent.preventDefault();
      this.contextRow = event.dataItem;
      this.rowMenuItems = [{ text: 'Copy B PDF' }];
      this.rowMenu.show({ left: event.originalEvent.pageX, top: event.originalEvent.pageY });
    } else {
      this.openDetail(event.dataItem);
    }
  }

  onRowMenuSelect(event: ContextMenuSelectEvent): void {
    if (!this.contextRow) return;
    if (event.item.text === 'Copy B PDF') this.copyB(this.contextRow);
  }

  openDetail(row: Form1099RecipientRow): void {
    this.detail = null;
    this.detailLoading = true;
    this.api.getRecipient(row.payeeId, this.taxYear).subscribe({
      next: (detail) => {
        this.detail = detail;
        this.detailLoading = false;
      },
      error: () => { this.detailLoading = false; },
    });
  }

  closeDetail(): void {
    this.detail = null;
    this.detailLoading = false;
  }

  // ── Downloads: fetched as blobs so the auth interceptor attaches the token ──────
  exportCsv(): void {
    this.api.downloadCsv(this.taxYear).subscribe((blob) => {
      this.saveBlob(blob, `1099-filing-${this.taxYear}.csv`);
    });
  }

  copyB(row: Form1099RecipientRow): void {
    this.api.downloadCopyB(row.payeeId, this.taxYear).subscribe((blob) => {
      this.saveBlob(blob, `1099-NEC-${row.payeeId}-${this.taxYear}.pdf`);
    });
  }

  /** Trigger a browser save of a downloaded blob via a temporary anchor. */
  private saveBlob(blob: Blob, fileName: string): void {
    const url = URL.createObjectURL(blob);
    const anchor = document.createElement('a');
    anchor.href = url;
    anchor.download = fileName;
    document.body.appendChild(anchor);
    anchor.click();
    document.body.removeChild(anchor);
    setTimeout(() => URL.revokeObjectURL(url), 60_000);
  }
}
