import { Component, inject, signal, computed } 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 { TabsModule } from 'primeng/tabs';
import { TableModule } from 'primeng/table';
import { ToastModule } from 'primeng/toast';
import { ChartModule } from 'primeng/chart';
import { TagModule } from 'primeng/tag';
import { DatePickerModule } from 'primeng/datepicker';
import { InputNumberModule } from 'primeng/inputnumber';
import { MessageService } from 'primeng/api';
import {
  InventoryReportService,
  MovementSummaryReport,
  WarehouseSummaryReport,
  SlowMovingReport,
  ExpiryReport,
  ValuationReport,
  ValuationItem,
} from '../../core/services/inventory-report.service';

@Component({
  selector: 'app-inventory-reports',
  standalone: true,
  imports: [
    CommonModule, FormsModule, TranslateModule,
    ButtonModule, TabsModule, TableModule,
    ToastModule, ChartModule, TagModule,
    DatePickerModule, InputNumberModule,
  ],
  providers: [MessageService],
  templateUrl: './inventory-reports.component.html',
  styleUrl: './inventory-reports.component.scss',
})
export class InventoryReportsComponent {
  private reportService = inject(InventoryReportService);
  private messageService = inject(MessageService);
  private translate = inject(TranslateService);

  activeTab = signal(0);

  // ─── Movement Summary ───
  msDateFrom = new Date(new Date().getFullYear(), 0, 1);
  msDateTo = new Date();
  movementData = signal<MovementSummaryReport | null>(null);
  loadingMovement = signal(false);

  // ─── Warehouse Summary ───
  warehouseData = signal<WarehouseSummaryReport | null>(null);
  loadingWarehouse = signal(false);

  // ─── Slow Moving ───
  smDays: number = 90;
  slowMovingData = signal<SlowMovingReport | null>(null);
  loadingSlow = signal(false);

  // ─── Expiry Tracking ───
  expiryDate = new Date();
  expiryData = signal<ExpiryReport | null>(null);
  loadingExpiry = signal(false);

  // ─── Valuation ───
  valDate = new Date();
  valuationData = signal<ValuationReport | null>(null);
  loadingValuation = signal(false);

  // Valuation computed: group by product
  valuationGrouped = computed(() => {
    const data = this.valuationData();
    if (!data?.items?.length) return [];
    const map = new Map<number, { product_name: string; product_code: string; items: ValuationItem[]; total_qty: number; total_value: number }>();
    for (const item of data.items) {
      const key = item.product_id;
      if (!map.has(key)) {
        map.set(key, { product_name: item.product_name, product_code: item.product_code, items: [], total_qty: 0, total_value: 0 });
      }
      const group = map.get(key)!;
      group.items.push(item);
      group.total_qty += item.quantity;
      group.total_value += item.total_value;
    }
    return Array.from(map.values());
  });

  // Valuation charts
  valProductChartData = computed(() => {
    const grouped = this.valuationGrouped();
    if (!grouped.length) return null;
    const colors = ['#6366f1', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#14b8a6', '#f97316'];
    return {
      labels: grouped.map(g => g.product_name),
      datasets: [{
        data: grouped.map(g => g.total_value),
        backgroundColor: grouped.map((_, i) => colors[i % colors.length]),
      }]
    };
  });

  valWarehouseChartData = computed(() => {
    const data = this.valuationData();
    if (!data?.items?.length) return null;
    const whMap = new Map<string, number>();
    for (const item of data.items) {
      whMap.set(item.warehouse_name, (whMap.get(item.warehouse_name) || 0) + item.total_value);
    }
    const labels = Array.from(whMap.keys());
    return {
      labels,
      datasets: [{
        label: this.translate.instant('INVENTORY.TOTAL_VALUE'),
        data: labels.map(l => whMap.get(l)!),
        backgroundColor: '#6366f1',
        borderRadius: 6,
      }]
    };
  });

  pieOptions: any = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: { legend: { position: 'bottom', labels: { padding: 16 } } }
  };

  barOptions: any = {
    indexAxis: 'y',
    responsive: true,
    maintainAspectRatio: false,
    plugins: { legend: { display: false } },
    scales: {
      x: { beginAtZero: true, grid: { color: 'rgba(0,0,0,0.05)' } },
      y: { grid: { display: false } }
    }
  };

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

  // ─── Load Methods ───
  loadMovementSummary(): void {
    this.loadingMovement.set(true);
    this.reportService.getMovementSummary(this.fmt(this.msDateFrom), this.fmt(this.msDateTo)).subscribe({
      next: (res) => { this.movementData.set(res.data); this.loadingMovement.set(false); },
      error: (err) => { this.loadingMovement.set(false); this.showError(err); },
    });
  }

  loadWarehouseSummary(): void {
    this.loadingWarehouse.set(true);
    this.reportService.getWarehouseSummary().subscribe({
      next: (res) => { this.warehouseData.set(res.data); this.loadingWarehouse.set(false); },
      error: (err) => { this.loadingWarehouse.set(false); this.showError(err); },
    });
  }

  loadSlowMoving(): void {
    this.loadingSlow.set(true);
    this.reportService.getSlowMoving(this.smDays).subscribe({
      next: (res) => { this.slowMovingData.set(res.data); this.loadingSlow.set(false); },
      error: (err) => { this.loadingSlow.set(false); this.showError(err); },
    });
  }

  loadExpiryReport(): void {
    this.loadingExpiry.set(true);
    this.reportService.getExpiryReport(this.fmt(this.expiryDate)).subscribe({
      next: (res) => { this.expiryData.set(res.data); this.loadingExpiry.set(false); },
      error: (err) => { this.loadingExpiry.set(false); this.showError(err); },
    });
  }

  loadValuation(): void {
    this.loadingValuation.set(true);
    this.reportService.getValuation(this.fmt(this.valDate)).subscribe({
      next: (res) => { this.valuationData.set(res.data); this.loadingValuation.set(false); },
      error: (err) => { this.loadingValuation.set(false); this.showError(err); },
    });
  }

  private showError(err: any): void {
    this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: err.error?.message || 'Failed' });
  }

  private fmt(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}`;
  }
}
