import { Component, OnInit, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { GridModule, CellClickEvent, RowClassArgs } 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 { DropDownsModule } from '@progress/kendo-angular-dropdowns';
import { ContextMenuModule, ContextMenuComponent, ContextMenuSelectEvent } from '@progress/kendo-angular-menu';
import { ExpenseCategoryApiService } from '../../services/expense-category-api.service';
import { ExpenseCategoryGroupDto, ExpenseSubCategoryDto, CategoryAiSuggestion } from '../../models/expense.model';
import { Form990ExpenseLineDto } from '../../../finance-report/models/form990-report.model';
import { Form1099Box } from '../../../payee1099/models/payee1099.model';

@Component({
  selector: 'app-expense-categories-page',
  standalone: true,
  imports: [CommonModule, FormsModule, GridModule, ButtonsModule, DialogsModule, InputsModule, DropDownsModule, ContextMenuModule],
  templateUrl: './expense-categories-page.component.html',
  styleUrls: ['./expense-categories-page.component.scss'],
})
export class ExpenseCategoriesPageComponent implements OnInit {
  groups: ExpenseCategoryGroupDto[] = [];
  selectedGroup: ExpenseCategoryGroupDto | null = null;
  loading = false;
  form990Lines: Form990ExpenseLineDto[] = [];
  form1099Boxes: (Form1099Box & { label: string })[] = [];

  @ViewChild('groupMenu') groupMenu!: ContextMenuComponent;
  @ViewChild('subMenu') subMenu!: ContextMenuComponent;
  groupMenuItems: { text: string }[] = [];
  subMenuItems: { text: string }[] = [];
  private contextGroup: ExpenseCategoryGroupDto | null = null;
  private contextSub: ExpenseSubCategoryDto | null = null;

  groupDialogOpen = false;
  editingGroupId: number | null = null;
  groupForm = { name_en: '', name_zh: '', sortOrder: 0, isActive: true, form990LineId: null as number | null, form1099BoxId: null as number | null };
  groupAiLoading = false;
  groupAiSuggestion: CategoryAiSuggestion | null = null;

  subDialogOpen = false;
  editingSubId: number | null = null;
  subForm = { name_en: '', name_zh: '', sortOrder: 0, isActive: true, form990LineId: null as number | null, form1099BoxId: null as number | null };
  subAiLoading = false;
  subAiSuggestion: CategoryAiSuggestion | null = null;

  constructor(private api: ExpenseCategoryApiService) {}

  ngOnInit(): void {
    this.load();
    this.api.getForm990Lines().subscribe(lines => { this.form990Lines = lines; });
    this.api.getForm1099Boxes().subscribe(boxes => { this.form1099Boxes = boxes; });
  }

  load(): void {
    this.loading = true;
    this.api.getAll(true).subscribe({
      next: g => {
        this.groups = g;
        if (this.selectedGroup) this.selectedGroup = g.find(x => x.id === this.selectedGroup!.id) ?? null;
        this.loading = false;
      },
      error: () => { this.loading = false; },
    });
  }

  selectGroup(g: ExpenseCategoryGroupDto): void { this.selectedGroup = g; }
  get subCategories(): ExpenseSubCategoryDto[] { return this.selectedGroup?.subCategories ?? []; }

  // Highlight the currently selected group row.
  groupRowClass = (context: RowClassArgs): Record<string, boolean> => {
    return { 'selected-row': this.selectedGroup?.id === context.dataItem.id };
  };

  // Left-click selects the group (reveals its subcategories); right-click opens the actions menu.
  onGroupCellClick(event: CellClickEvent): void {
    if (event.type === 'contextmenu') {
      event.originalEvent.preventDefault();
      this.contextGroup = event.dataItem;
      this.groupMenuItems = this.buildMenuItems(event.dataItem.isActive);
      this.groupMenu.show({ left: event.originalEvent.pageX, top: event.originalEvent.pageY });
    } else {
      this.selectGroup(event.dataItem);
    }
  }

  onGroupMenuSelect(event: ContextMenuSelectEvent): void {
    if (!this.contextGroup) return;
    if (event.item.text === 'Edit') this.openEditGroup(this.contextGroup);
    else if (event.item.text === 'Deactivate') this.deactivateGroup(this.contextGroup);
  }

  // Subcategory rows have no selection behaviour; only the right-click actions menu.
  onSubCellClick(event: CellClickEvent): void {
    if (event.type !== 'contextmenu') return;
    event.originalEvent.preventDefault();
    this.contextSub = event.dataItem;
    this.subMenuItems = this.buildMenuItems(event.dataItem.isActive);
    this.subMenu.show({ left: event.originalEvent.pageX, top: event.originalEvent.pageY });
  }

  onSubMenuSelect(event: ContextMenuSelectEvent): void {
    if (!this.contextSub) return;
    if (event.item.text === 'Edit') this.openEditSub(this.contextSub);
    else if (event.item.text === 'Deactivate') this.deactivateSub(this.contextSub);
  }

  private buildMenuItems(isActive: boolean): { text: string }[] {
    const items: { text: string }[] = [{ text: 'Edit' }];
    if (isActive) items.push({ text: 'Deactivate' });
    return items;
  }

  openNewGroup(): void {
    this.editingGroupId = null;
    this.groupForm = { name_en: '', name_zh: '', sortOrder: this.groups.length + 1, isActive: true, form990LineId: null, form1099BoxId: null };
    this.resetGroupAi();
    this.groupDialogOpen = true;
  }
  openEditGroup(g: ExpenseCategoryGroupDto): void {
    this.editingGroupId = g.id;
    this.groupForm = { name_en: g.name_en, name_zh: g.name_zh ?? '', sortOrder: g.sortOrder, isActive: g.isActive, form990LineId: g.form990LineId, form1099BoxId: g.form1099BoxId };
    this.resetGroupAi();
    this.groupDialogOpen = true;
  }

  // ── Group AI assist: refine the Chinese name, translate to English, suggest a Form 990 line ──
  private resetGroupAi(): void { this.groupAiLoading = false; this.groupAiSuggestion = null; }
  requestGroupAiSuggest(): void {
    if (this.groupAiLoading) return;
    this.groupAiLoading = true;
    this.groupAiSuggestion = null;
    this.api.aiSuggest({ name_zh: this.groupForm.name_zh.trim(), name_en: this.groupForm.name_en.trim() || null, level: 'group' }).subscribe({
      next: s => { this.groupAiSuggestion = s; this.groupAiLoading = false; },
      error: () => { this.groupAiLoading = false; },
    });
  }
  applyGroupAiSuggestion(): void {
    const s = this.groupAiSuggestion;
    if (!s) return;
    if (s.chineseName) this.groupForm.name_zh = s.chineseName;
    if (s.englishName) this.groupForm.name_en = s.englishName;
    if (s.form990LineId != null) this.groupForm.form990LineId = s.form990LineId;
    this.groupAiSuggestion = null;
  }
  dismissGroupAiSuggestion(): void { this.groupAiSuggestion = null; }
  saveGroup(): void {
    const body = { name_en: this.groupForm.name_en, name_zh: this.groupForm.name_zh || null, sortOrder: this.groupForm.sortOrder, form990LineId: this.groupForm.form990LineId, form1099BoxId: this.groupForm.form1099BoxId };
    const done = () => { this.groupDialogOpen = false; this.load(); };
    if (this.editingGroupId == null) this.api.createGroup(body).subscribe(done);
    else this.api.updateGroup(this.editingGroupId, { ...body, isActive: this.groupForm.isActive }).subscribe(done);
  }
  deactivateGroup(g: ExpenseCategoryGroupDto): void {
    if (!confirm(`Deactivate "${g.name_en}"?`)) return;
    this.api.deactivateGroup(g.id).subscribe(() => this.load());
  }

  openNewSub(): void {
    if (!this.selectedGroup) return;
    this.editingSubId = null;
    this.subForm = { name_en: '', name_zh: '', sortOrder: this.subCategories.length + 1, isActive: true, form990LineId: null, form1099BoxId: null };
    this.resetSubAi();
    this.subDialogOpen = true;
  }
  openEditSub(s: ExpenseSubCategoryDto): void {
    this.editingSubId = s.id;
    this.subForm = { name_en: s.name_en, name_zh: s.name_zh ?? '', sortOrder: s.sortOrder, isActive: s.isActive, form990LineId: s.form990LineId, form1099BoxId: s.form1099BoxId };
    this.resetSubAi();
    this.subDialogOpen = true;
  }

  // ── Subcategory AI assist: same as group, biased by the selected parent group + its 990 line ──
  private resetSubAi(): void { this.subAiLoading = false; this.subAiSuggestion = null; }
  requestSubAiSuggest(): void {
    if (this.subAiLoading || !this.selectedGroup) return;
    this.subAiLoading = true;
    this.subAiSuggestion = null;
    this.api.aiSuggest({
      name_zh: this.subForm.name_zh.trim(),
      name_en: this.subForm.name_en.trim() || null,
      level: 'sub',
      parentGroupName: this.selectedGroup.label ?? this.selectedGroup.name_en,
      parentForm990LineId: this.selectedGroup.form990LineId,
    }).subscribe({
      next: s => { this.subAiSuggestion = s; this.subAiLoading = false; },
      error: () => { this.subAiLoading = false; },
    });
  }
  applySubAiSuggestion(): void {
    const s = this.subAiSuggestion;
    if (!s) return;
    if (s.chineseName) this.subForm.name_zh = s.chineseName;
    if (s.englishName) this.subForm.name_en = s.englishName;
    if (s.form990LineId != null) this.subForm.form990LineId = s.form990LineId;
    this.subAiSuggestion = null;
  }
  dismissSubAiSuggestion(): void { this.subAiSuggestion = null; }
  saveSub(): void {
    if (!this.selectedGroup) return;
    const body = { groupId: this.selectedGroup.id, name_en: this.subForm.name_en, name_zh: this.subForm.name_zh || null, sortOrder: this.subForm.sortOrder, form990LineId: this.subForm.form990LineId, form1099BoxId: this.subForm.form1099BoxId };
    const done = () => { this.subDialogOpen = false; this.load(); };
    if (this.editingSubId == null) this.api.createSub(body).subscribe(done);
    else this.api.updateSub(this.editingSubId, { ...body, isActive: this.subForm.isActive }).subscribe(done);
  }
  deactivateSub(s: ExpenseSubCategoryDto): void {
    if (!confirm(`Deactivate "${s.name_en}"?`)) return;
    this.api.deactivateSub(s.id).subscribe(() => this.load());
  }
}
