import { Component, OnInit, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { TabsModule } from 'primeng/tabs';
import { TableModule } from 'primeng/table';
import { ButtonModule } from 'primeng/button';
import { DatePickerModule } from 'primeng/datepicker';
import { CardModule } from 'primeng/card';
import { ToastModule } from 'primeng/toast';
import { ProgressSpinnerModule } from 'primeng/progressspinner';
import { MessageService } from 'primeng/api';
import { PageHeaderComponent } from '../../../shared/components/page-header/page-header.component';
import { HrReportService } from '../../../core/services/hr-report.service';

@Component({
  selector: 'app-hr-reports',
  standalone: true,
  imports: [
    CommonModule, FormsModule, TranslateModule,
    TabsModule, TableModule, ButtonModule, DatePickerModule,
    CardModule, ToastModule, ProgressSpinnerModule,
    PageHeaderComponent,
  ],
  providers: [MessageService],
  templateUrl: './hr-reports.component.html',
  styleUrl: './hr-reports.component.scss',
})
export class HrReportsComponent implements OnInit {
  private reportService = inject(HrReportService);
  private messageService = inject(MessageService);
  private translate = inject(TranslateService);

  loading = signal(false);
  activeTab = signal(0);

  dateFrom: Date | null = null;
  dateTo: Date | null = null;

  workforceData = signal<any>(null);
  attendanceData = signal<any>(null);
  leaveData = signal<any>(null);
  payrollData = signal<any>(null);
  loansData = signal<any>(null);
  turnoverData = signal<any>(null);

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

  onTabChange(value: string | number | undefined): void {
    this.activeTab.set(Number(value) || 0);
    this.generateReport();
  }

  generateReport(): void {
    const filters: Record<string, any> = {};
    if (this.dateFrom) filters['date_from'] = this.formatDate(this.dateFrom);
    if (this.dateTo) filters['date_to'] = this.formatDate(this.dateTo);

    this.loading.set(true);

    const tab = this.activeTab();
    const reportMap: Record<number, { method: string; signal: any }> = {
      0: { method: 'getWorkforceReport', signal: this.workforceData },
      1: { method: 'getAttendanceReport', signal: this.attendanceData },
      2: { method: 'getLeaveReport', signal: this.leaveData },
      3: { method: 'getPayrollSummaryReport', signal: this.payrollData },
      4: { method: 'getLoansReport', signal: this.loansData },
      5: { method: 'getTurnoverReport', signal: this.turnoverData },
    };

    const config = reportMap[tab];
    if (config) {
      (this.reportService as any)[config.method](filters).subscribe({
        next: (res: any) => {
          config.signal.set(res.data || res);
          this.loading.set(false);
        },
        error: (err: any) => {
          this.loading.set(false);
          this.messageService.add({
            severity: 'error',
            summary: this.translate.instant('COMMON.ERROR'),
            detail: err.error?.message || 'Failed to load report',
          });
        },
      });
    }
  }

  private formatDate(date: Date): string {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
  }
}
