import { Component, inject, OnInit, signal, computed } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { ButtonModule } from 'primeng/button';
import { ChartModule } from 'primeng/chart';
import { TagModule } from 'primeng/tag';
import { ProgressSpinnerModule } from 'primeng/progressspinner';
import { TableModule } from 'primeng/table';
import { TooltipModule } from 'primeng/tooltip';
import { forkJoin } from 'rxjs';
import { PageHeaderComponent } from '../../../shared';
import { PurchaseReportService } from '../../../core/services/purchase-report.service';

@Component({
  selector: 'app-purchases-dashboard',
  standalone: true,
  imports: [
    CommonModule, RouterModule, TranslateModule, ButtonModule, ChartModule,
    TagModule, ProgressSpinnerModule, TableModule, TooltipModule, PageHeaderComponent,
  ],
  templateUrl: './purchases-dashboard.component.html',
  styleUrl: './purchases-dashboard.component.scss',
})
export class PurchasesDashboardComponent implements OnInit {
  private reportService = inject(PurchaseReportService);
  private translate = inject(TranslateService);

  loading = signal(true);
  error = signal(false);

  summary = signal<any>(null);
  trendsData = signal<any>(null);
  categoryData = signal<any>(null);
  supplierData = signal<any>(null);
  overdueItems = signal<any[]>([]);
  overdueTotal = signal(0);

  lineChartOptions: any = {
    responsive: true, maintainAspectRatio: false,
    plugins: { legend: { position: 'bottom' } },
    scales: { y: { beginAtZero: true, ticks: { callback: (v: number) => v.toLocaleString() } } },
  };
  doughnutChartOptions: any = {
    responsive: true, maintainAspectRatio: false,
    plugins: { legend: { position: 'bottom' } },
  };
  barChartOptions: any = {
    responsive: true, maintainAspectRatio: false, indexAxis: 'y' as const,
    plugins: { legend: { display: false } },
    scales: { x: { beginAtZero: true, ticks: { callback: (v: number) => v.toLocaleString() } } },
  };

  totalPurchases = computed(() => {
    const s = this.summary();
    return s ? parseFloat(s.bills?.value || 0) : 0;
  });

  outstanding = computed(() => {
    const s = this.summary();
    return s ? parseFloat(s.amount_outstanding || 0) : 0;
  });

  netPurchases = computed(() => {
    const s = this.summary();
    return s ? parseFloat(s.net_purchases || 0) : 0;
  });

  poCount = computed(() => {
    const s = this.summary();
    return s ? (s.purchase_orders?.count || 0) : 0;
  });

  prCount = computed(() => {
    const s = this.summary();
    return s ? (s.purchase_requests?.count || 0) : 0;
  });

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

  loadDashboard(): void {
    this.loading.set(true);
    this.error.set(false);

    forkJoin({
      summary: this.reportService.summary(),
      trends: this.reportService.trends(),
      category: this.reportService.byCategory(),
      supplier: this.reportService.bySupplier({ limit: 10 }),
      overdue: this.reportService.overdueBills(),
    }).subscribe({
      next: (res) => {
        this.summary.set(res.summary.data);
        this.buildTrendsChart(res.trends.data || []);
        this.buildCategoryChart(res.category.data || []);
        this.buildSupplierChart(res.supplier.data || []);
        this.processOverdue(res.overdue.data);
        this.loading.set(false);
      },
      error: () => { this.loading.set(false); this.error.set(true); },
    });
  }

  private buildTrendsChart(data: any[]): void {
    const labels = data.map(d => d.period_label || d.period);
    this.trendsData.set({
      labels,
      datasets: [
        { label: this.translate.instant('PURCHASES.TOTAL'), data: data.map(d => parseFloat(d.total_cost || 0)), borderColor: '#3b82f6', backgroundColor: 'rgba(59,130,246,0.1)', fill: true, tension: 0.4 },
        { label: this.translate.instant('PURCHASES.RETURNS'), data: data.map(d => parseFloat(d.returns || 0)), borderColor: '#ef4444', backgroundColor: 'rgba(239,68,68,0.1)', fill: true, tension: 0.4 },
        { label: this.translate.instant('PURCHASES.NET_PURCHASES'), data: data.map(d => parseFloat(d.net || 0)), borderColor: '#10b981', backgroundColor: 'rgba(16,185,129,0.1)', fill: true, tension: 0.4 },
      ],
    });
  }

  private buildCategoryChart(data: any[]): void {
    if (!data.length) { this.categoryData.set(null); return; }
    const colors = ['#3b82f6', '#ef4444', '#10b981', '#f59e0b', '#8b5cf6', '#ec4899', '#06b6d4', '#84cc16'];
    this.categoryData.set({
      labels: data.map(d => d.category_name || d.name || 'Other'),
      datasets: [{ data: data.map(d => parseFloat(d.total_cost || d.total_spend || 0)), backgroundColor: colors.slice(0, data.length) }],
    });
  }

  private buildSupplierChart(data: any[]): void {
    if (!data.length) { this.supplierData.set(null); return; }
    const top10 = data.slice(0, 10);
    this.supplierData.set({
      labels: top10.map(d => d.name || d.supplier_name),
      datasets: [{ data: top10.map(d => parseFloat(d.total_spend || d.net_spend || 0)), backgroundColor: '#3b82f6', borderRadius: 4 }],
    });
  }

  private processOverdue(data: any): void {
    if (data?.items) {
      this.overdueItems.set(data.items || []);
      this.overdueTotal.set(parseFloat(data.total_overdue || 0));
    } else if (Array.isArray(data)) {
      this.overdueItems.set(data);
      this.overdueTotal.set(data.reduce((sum: number, d: any) => sum + parseFloat(d.balance_due || 0), 0));
    }
  }

  retry(): void { this.loadDashboard(); }
}
