import { Component, inject, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { ButtonModule } from 'primeng/button';
import { ChartModule } from 'primeng/chart';
import { TableModule } from 'primeng/table';
import { TagModule } from 'primeng/tag';
import { TabsModule } from 'primeng/tabs';
import { DatePickerModule } from 'primeng/datepicker';
import { SelectModule } from 'primeng/select';
import { ToastModule } from 'primeng/toast';
import { ProgressSpinnerModule } from 'primeng/progressspinner';
import { TooltipModule } from 'primeng/tooltip';
import { MessageService } from 'primeng/api';
import { PageHeaderComponent } from '../../../shared';
import { SalesReportService } from '../../../core/services/sales-report.service';
import { ExportService } from '../../../core/services/export.service';

@Component({
  selector: 'app-sales-reports',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    TranslateModule,
    ButtonModule,
    ChartModule,
    TableModule,
    TagModule,
    TabsModule,
    DatePickerModule,
    SelectModule,
    ToastModule,
    ProgressSpinnerModule,
    TooltipModule,
    PageHeaderComponent,
  ],
  providers: [MessageService],
  templateUrl: './sales-reports.component.html',
  styleUrl: './sales-reports.component.scss',
})
export class SalesReportsComponent implements OnInit {
  private service = inject(SalesReportService);
  private messageService = inject(MessageService);
  private translate = inject(TranslateService);
  private exportService = inject(ExportService);

  activeTab = signal('summary');
  loading = signal(false);

  // Filters
  dateRange: Date[] = [];

  // Summary
  summaryData = signal<any>(null);
  summaryChart = signal<any>(null);

  // By Product
  productData = signal<any[]>([]);
  productChart = signal<any>(null);

  // By Customer
  customerData = signal<any[]>([]);
  customerChart = signal<any>(null);

  // By Salesperson
  salespersonData = signal<any[]>([]);
  salespersonChart = signal<any>(null);

  // Trends
  trendsData = signal<any[]>([]);
  trendsChart = signal<any>(null);

  // Overdue
  overdueData = signal<any[]>([]);
  agingBuckets = signal<any>(null);

  // Conversion Funnel
  funnelData = signal<any>(null);
  funnelChart = signal<any>(null);

  // Chart options
  barOptions: any = {
    responsive: true, maintainAspectRatio: false,
    plugins: { legend: { display: false } },
    scales: { y: { beginAtZero: true } },
  };

  horizontalBarOptions: any = {
    responsive: true, maintainAspectRatio: false,
    indexAxis: 'y' as const,
    plugins: { legend: { display: false } },
    scales: { x: { beginAtZero: true } },
  };

  lineOptions: any = {
    responsive: true, maintainAspectRatio: false,
    plugins: { legend: { position: 'bottom' } },
    scales: { y: { beginAtZero: true } },
  };

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

  onTabChange(tab: string): void {
    this.activeTab.set(tab);
    switch (tab) {
      case 'summary': this.loadSummary(); break;
      case 'product': this.loadByProduct(); break;
      case 'customer': this.loadByCustomer(); break;
      case 'salesperson': this.loadBySalesperson(); break;
      case 'trends': this.loadTrends(); break;
      case 'overdue': this.loadOverdue(); break;
      case 'funnel': this.loadFunnel(); break;
    }
  }

  private getFilters(): Record<string, any> {
    const f: Record<string, any> = {};
    if (this.dateRange?.length === 2 && this.dateRange[0] && this.dateRange[1]) {
      f['date_from'] = this.formatDate(this.dateRange[0]);
      f['date_to'] = this.formatDate(this.dateRange[1]);
    }
    return f;
  }

  private formatDate(d: Date): string {
    return d.toISOString().split('T')[0];
  }

  generateReport(): void {
    this.onTabChange(this.activeTab());
  }

  // ─── Summary ──────────────────────────────────────────

  loadSummary(): void {
    this.loading.set(true);
    this.service.summary(this.getFilters()).subscribe({
      next: (res) => {
        this.summaryData.set(res.data);
        this.buildSummaryChart(res.data);
        this.loading.set(false);
      },
      error: () => this.loading.set(false),
    });
  }

  private buildSummaryChart(data: any): void {
    if (!data) return;
    this.summaryChart.set({
      labels: [
        this.translate.instant('SALES.QUOTATIONS'),
        this.translate.instant('SALES.ORDERS'),
        this.translate.instant('SALES.INVOICES'),
        this.translate.instant('SALES.RETURNS'),
      ],
      datasets: [{
        data: [
          parseFloat(data.quotations?.value || data.quotations_value || 0),
          parseFloat(data.orders?.value || data.orders_value || 0),
          parseFloat(data.invoices?.value || data.invoices_value || 0),
          parseFloat(data.returns?.value || data.returns_value || 0),
        ],
        backgroundColor: ['#3b82f6', '#f59e0b', '#10b981', '#ef4444'],
      }],
    });
  }

  getSummaryValue(key: string): number {
    const d = this.summaryData();
    if (!d) return 0;
    if (key === 'quotations_count') return d.quotations?.count ?? d.quotations_count ?? 0;
    if (key === 'orders_count') return d.orders?.count ?? d.orders_count ?? 0;
    if (key === 'invoices_count') return d.invoices?.count ?? d.invoices_count ?? 0;
    if (key === 'returns_count') return d.returns?.count ?? d.returns_count ?? 0;
    if (key === 'quotations_value') return parseFloat(d.quotations?.value ?? d.quotations_value ?? 0);
    if (key === 'orders_value') return parseFloat(d.orders?.value ?? d.orders_value ?? 0);
    if (key === 'invoices_value') return parseFloat(d.invoices?.value ?? d.invoices_value ?? 0);
    if (key === 'returns_value') return parseFloat(d.returns?.value ?? d.returns_value ?? 0);
    return parseFloat(d[key] ?? 0);
  }

  // ─── By Product ───────────────────────────────────────

  loadByProduct(): void {
    this.loading.set(true);
    this.service.byProduct(this.getFilters()).subscribe({
      next: (res) => {
        this.productData.set(res.data || []);
        this.buildProductChart(res.data || []);
        this.loading.set(false);
      },
      error: () => this.loading.set(false),
    });
  }

  private buildProductChart(data: any[]): void {
    const top10 = data.slice(0, 10);
    this.productChart.set({
      labels: top10.map(d => d.product_name || d.name),
      datasets: [{
        data: top10.map(d => parseFloat(d.total_sales || d.gross_revenue || d.net_revenue || 0)),
        backgroundColor: '#3b82f6',
        borderRadius: 4,
      }],
    });
  }

  // ─── By Customer ──────────────────────────────────────

  loadByCustomer(): void {
    this.loading.set(true);
    this.service.byCustomer(this.getFilters()).subscribe({
      next: (res) => {
        this.customerData.set(res.data || []);
        this.buildCustomerChart(res.data || []);
        this.loading.set(false);
      },
      error: () => this.loading.set(false),
    });
  }

  private buildCustomerChart(data: any[]): void {
    const top10 = data.slice(0, 10);
    this.customerChart.set({
      labels: top10.map(d => d.customer_name || d.name),
      datasets: [{
        data: top10.map(d => parseFloat(d.total_sales || d.gross_revenue || d.net_sales || 0)),
        backgroundColor: '#10b981',
        borderRadius: 4,
      }],
    });
  }

  // ─── By Salesperson ───────────────────────────────────

  loadBySalesperson(): void {
    this.loading.set(true);
    this.service.bySalesperson(this.getFilters()).subscribe({
      next: (res) => {
        this.salespersonData.set(res.data || []);
        this.buildSalespersonChart(res.data || []);
        this.loading.set(false);
      },
      error: () => this.loading.set(false),
    });
  }

  private buildSalespersonChart(data: any[]): void {
    this.salespersonChart.set({
      labels: data.map(d => d.salesperson_name || d.name || 'N/A'),
      datasets: [{
        data: data.map(d => parseFloat(d.total_sales || d.revenue || 0)),
        backgroundColor: '#8b5cf6',
        borderRadius: 4,
      }],
    });
  }

  // ─── Trends ───────────────────────────────────────────

  loadTrends(): void {
    this.loading.set(true);
    this.service.trends(this.getFilters()).subscribe({
      next: (res) => {
        this.trendsData.set(res.data || []);
        this.buildTrendsChart(res.data || []);
        this.loading.set(false);
      },
      error: () => this.loading.set(false),
    });
  }

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

  // ─── Overdue ──────────────────────────────────────────

  loadOverdue(): void {
    this.loading.set(true);
    this.service.overdueInvoices(this.getFilters()).subscribe({
      next: (res: any) => {
        const data = res.data;
        if (Array.isArray(data)) {
          this.overdueData.set(data);
          this.agingBuckets.set(null);
        } else {
          this.overdueData.set(data?.items || []);
          this.agingBuckets.set(data?.aging_buckets || null);
        }
        this.loading.set(false);
      },
      error: () => this.loading.set(false),
    });
  }

  getAgingValue(key: string): number {
    const b = this.agingBuckets();
    return b ? parseFloat(b[key] || 0) : 0;
  }

  // ─── Conversion Funnel ────────────────────────────────

  loadFunnel(): void {
    this.loading.set(true);
    this.service.conversionFunnel(this.getFilters()).subscribe({
      next: (res) => {
        this.funnelData.set(res.data);
        this.buildFunnelChart(res.data);
        this.loading.set(false);
      },
      error: () => this.loading.set(false),
    });
  }

  private buildFunnelChart(data: any): void {
    if (!data) return;
    this.funnelChart.set({
      labels: [
        this.translate.instant('SALES.QUOTATIONS'),
        this.translate.instant('SALES.ORDERS'),
        this.translate.instant('SALES.INVOICES'),
      ],
      datasets: [{
        data: [
          data.total_quotations || data.quotations_created || 0,
          data.total_orders || data.converted_to_orders || 0,
          data.total_invoices || data.converted_to_invoices || 0,
        ],
        backgroundColor: ['#3b82f6', '#f59e0b', '#10b981'],
        borderRadius: 4,
      }],
    });
  }

  // ─── Export ───────────────────────────────────────────

  exportExcel(data: any[], filename: string): void {
    if (!data?.length) return;
    const columns = Object.keys(data[0]).map((k) => ({ field: k, header: k.replace(/_/g, ' ').toUpperCase() }));
    this.exportService.exportExcel(data, columns, filename);
  }

  // ─── Helpers ──────────────────────────────────────────

  retry(): void {
    this.onTabChange(this.activeTab());
  }
}
