'use client';

import React, { useMemo, useState } from 'react';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import type {
  CustomerPayment,
  InventoryMovement,
  JournalEntry,
  SalesInvoice,
} from '@/lib/types';
import type { MaterialFull, GroupLite } from '@/lib/reports/advanced-reporting';
import {
  buildProfitByInvoice,
  buildCustomerFrequency,
  buildInactiveCustomers,
  buildBestSellingTime,
  buildBranchPerformance,
  buildCategoryPerformance,
  buildCollectionRate,
  buildDSO,
  buildTopDebtors,
  buildDiscountAnalysis,
  buildPriceVariance,
  buildDailyPerformance,
  buildPeriodComparison,
  buildRevenueVsExpenses,
  buildDwellTime,
} from '@/lib/reports/advanced-reporting';

// ─── Helpers ─────────────────────────────────────────────────────────────────

function fmt(n: number, symbol: string) {
  return `${Number.isFinite(n) ? n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : '0.00'} ${symbol}`;
}

function pct(n: number) {
  return `${Number.isFinite(n) ? n.toFixed(1) : '0.0'}%`;
}

function growthBadge(value: number) {
  const color = value >= 0 ? 'text-green-600' : 'text-red-600';
  const sign = value >= 0 ? '▲' : '▼';
  return <span className={`${color} font-semibold text-xs`}>{sign} {Math.abs(value).toFixed(1)}%</span>;
}

// ─── Reusable Table ───────────────────────────────────────────────────────────

function ReportTable({ headers, rows }: { headers: string[]; rows: React.ReactNode[][] }) {
  if (rows.length === 0) {
    return <p className="text-sm text-muted-foreground py-6 text-center">لا توجد بيانات في هذه الفترة</p>;
  }
  return (
    <div className="overflow-x-auto rounded border">
      <table className="w-full text-sm text-right">
        <thead className="bg-muted/60 text-xs font-semibold">
          <tr>{headers.map((h, i) => <th key={i} className="px-3 py-2 whitespace-nowrap">{h}</th>)}</tr>
        </thead>
        <tbody>
          {rows.map((row, ri) => (
            <tr key={ri} className={ri % 2 === 0 ? 'bg-white dark:bg-background' : 'bg-muted/20'}>
              {row.map((cell, ci) => (
                <td key={ci} className="px-3 py-1.5 whitespace-nowrap">{cell}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ─── Metric Card ──────────────────────────────────────────────────────────────

function MetricCard({ label, value, sub }: { label: string; value: string; sub?: string }) {
  return (
    <div className="rounded-lg border bg-card p-4 shadow-sm text-center space-y-1">
      <p className="text-xs text-muted-foreground">{label}</p>
      <p className="text-xl font-bold">{value}</p>
      {sub && <p className="text-xs text-muted-foreground">{sub}</p>}
    </div>
  );
}

// ─── Props ────────────────────────────────────────────────────────────────────

type Props = {
  invoices: SalesInvoice[];
  payments: CustomerPayment[];
  inventoryMovements: InventoryMovement[];
  journalEntries: JournalEntry[];
  materials: MaterialFull[];
  groups: GroupLite[];
  currencySymbol: string;
  defaultDate: string;
};

// ─── Component ───────────────────────────────────────────────────────────────

export default function AdvancedReportsClient({
  invoices,
  payments,
  inventoryMovements,
  journalEntries,
  materials,
  groups,
  currencySymbol,
  defaultDate,
}: Props) {
  const [activeReport, setActiveReport] = useState('profit-invoice');

  // Global date filters
  const [fromDate, setFromDate] = useState('');
  const [toDate, setToDate] = useState('');
  const filters = useMemo(() => ({ fromDate: fromDate || undefined, toDate: toDate || undefined }), [fromDate, toDate]);

  // Period comparison state
  const [p1From, setP1From] = useState('');
  const [p1To, setP1To] = useState('');
  const [p2From, setP2From] = useState('');
  const [p2To, setP2To] = useState('');

  // Daily performance date
  const [dailyDate, setDailyDate] = useState(defaultDate);

  // Inactive customer threshold
  const [inactiveThreshold, setInactiveThreshold] = useState(90);

  const reportOptions = [
    { value: 'profit-invoice', label: 'ربحية الفاتورة' },
    { value: 'profit-margin', label: 'هامش الربح' },
    { value: 'price-variance', label: 'فجوة السعر/التكلفة' },
    { value: 'customer-freq', label: 'تكرار الشراء' },
    { value: 'inactive', label: 'عملاء غير نشطين' },
    { value: 'top-debtors', label: 'أعلى المديونيات' },
    { value: 'dwell-time', label: 'مدة بقاء الصنف' },
    { value: 'best-time', label: 'أفضل وقت للبيع' },
    { value: 'branch', label: 'أداء المستودعات' },
    { value: 'category', label: 'أداء الفئات' },
    { value: 'collection-rate', label: 'نسبة التحصيل' },
    { value: 'dso', label: 'متوسط فترة التحصيل' },
    { value: 'discounts', label: 'تحليل الخصومات' },
    { value: 'daily', label: 'الأداء اليومي' },
    { value: 'period-compare', label: 'مقارنة الفترات' },
    { value: 'rev-vs-exp', label: 'إيرادات مقابل مصاريف' },
  ] as const;

  // ── Computations ────────────────────────────────────────────────────────────

  const profitByInvoice = useMemo(() => buildProfitByInvoice(invoices, materials, filters), [invoices, materials, filters]);
  const freqRows = useMemo(() => buildCustomerFrequency(invoices, filters), [invoices, filters]);
  const inactiveRows = useMemo(() => buildInactiveCustomers(freqRows, inactiveThreshold), [freqRows, inactiveThreshold]);
  const bestTimeRows = useMemo(() => buildBestSellingTime(invoices, filters), [invoices, filters]);
  const branchRows = useMemo(() => buildBranchPerformance(invoices, materials, filters), [invoices, materials, filters]);
  const catRows = useMemo(() => buildCategoryPerformance(invoices, materials, groups, filters), [invoices, materials, groups, filters]);
  const collectionRate = useMemo(() => buildCollectionRate(invoices, filters), [invoices, filters]);
  const dso = useMemo(() => buildDSO(invoices, payments, filters), [invoices, payments, filters]);
  const topDebtors = useMemo(() => buildTopDebtors(invoices, filters), [invoices, filters]);
  const discountSummary = useMemo(() => buildDiscountAnalysis(invoices, filters), [invoices, filters]);
  const priceVarianceRows = useMemo(() => buildPriceVariance(invoices, materials, filters), [invoices, materials, filters]);
  const dailyPerf = useMemo(() => buildDailyPerformance(invoices, payments, dailyDate), [invoices, payments, dailyDate]);
  const periodComp = useMemo(() => {
    if (!p1From || !p1To || !p2From || !p2To) return null;
    return buildPeriodComparison(invoices, p1From, p1To, p2From, p2To);
  }, [invoices, p1From, p1To, p2From, p2To]);
  const revVsExp = useMemo(() => buildRevenueVsExpenses(journalEntries, filters), [journalEntries, filters]);
  const dwellRows = useMemo(() => buildDwellTime(inventoryMovements, materials, filters), [inventoryMovements, materials, filters]);

  // Profit summary from profitByInvoice
  const profitSummary = useMemo(() => {
    const totalSales = profitByInvoice.reduce((s, r) => s + r.salesValue, 0);
    const totalCost = profitByInvoice.reduce((s, r) => s + r.estimatedCost, 0);
    const totalProfit = totalSales - totalCost;
    return { totalSales, totalCost, totalProfit, margin: totalSales > 0 ? (totalProfit / totalSales) * 100 : 0 };
  }, [profitByInvoice]);

  // ── Date filter bar ─────────────────────────────────────────────────────────

  const dateBar = (
    <div className="mb-6 space-y-4">
      {/* Title */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <div className="w-1.5 h-6 bg-gradient-to-b from-blue-500 to-cyan-500 rounded-full shadow-md"></div>
          <h3 className="font-bold text-base bg-gradient-to-r from-blue-600 to-cyan-600 bg-clip-text text-transparent">فترة التقرير والإعدادات</h3>
        </div>
      </div>

      {/* Filter Card */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 p-5 rounded-xl bg-gradient-to-br from-blue-50/50 via-cyan-50/30 to-blue-50/40 dark:from-blue-950/20 dark:via-cyan-950/10 dark:to-blue-950/20 border border-blue-200/40 dark:border-blue-800/40 backdrop-blur-md shadow-lg shadow-blue-100/20 dark:shadow-blue-900/10">
        
        {/* Date Range Section */}
        <div className="md:col-span-2 flex flex-col gap-4">
          {/* Header for Date Section */}
          <div className="flex items-center gap-2 mb-1">
            <div className="w-4 h-4 rounded-full bg-gradient-to-r from-blue-500 to-blue-600 flex items-center justify-center">
              <span className="text-xs text-white">📅</span>
            </div>
            <span className="text-xs font-bold text-blue-700 dark:text-blue-300 uppercase tracking-widest">نطاق التواريخ</span>
          </div>

          <div className="grid grid-cols-2 gap-3">
            {/* From Date */}
            <label className="flex flex-col gap-2 p-3 rounded-lg bg-white/60 dark:bg-slate-900/40 border border-blue-200/30 dark:border-blue-700/30 hover:border-blue-300/60 dark:hover:border-blue-600/60 transition-all">
              <span className="text-xs font-semibold text-blue-600 dark:text-blue-400 uppercase tracking-widest">📍 من التاريخ</span>
              <input 
                type="date" 
                value={fromDate} 
                onChange={(e) => setFromDate(e.target.value)} 
                className="px-3 py-2 text-sm rounded-lg border border-blue-300/50 bg-gradient-to-r from-blue-50 to-cyan-50 dark:from-slate-800 dark:to-slate-800 hover:border-blue-400/70 focus:outline-none focus:ring-2 focus:ring-blue-500/60 focus:border-transparent transition-all font-medium" 
                dir="ltr"
              />
            </label>

            {/* To Date */}
            <label className="flex flex-col gap-2 p-3 rounded-lg bg-white/60 dark:bg-slate-900/40 border border-cyan-200/30 dark:border-cyan-700/30 hover:border-cyan-300/60 dark:hover:border-cyan-600/60 transition-all">
              <span className="text-xs font-semibold text-cyan-600 dark:text-cyan-400 uppercase tracking-widest">⏳ إلى التاريخ</span>
              <input 
                type="date" 
                value={toDate} 
                onChange={(e) => setToDate(e.target.value)} 
                className="px-3 py-2 text-sm rounded-lg border border-cyan-300/50 bg-gradient-to-r from-cyan-50 to-blue-50 dark:from-slate-800 dark:to-slate-800 hover:border-cyan-400/70 focus:outline-none focus:ring-2 focus:ring-cyan-500/60 focus:border-transparent transition-all font-medium" 
                dir="ltr"
              />
            </label>
          </div>

          {/* Reset Button */}
          {(fromDate || toDate) && (
            <button 
              onClick={() => { setFromDate(''); setToDate(''); }} 
              className="w-full px-4 py-2.5 text-xs font-bold text-white bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 rounded-lg border border-orange-400/50 hover:border-orange-500/70 transition-all duration-200 shadow-md hover:shadow-lg"
            >
              🔄 إعادة ضبط التواريخ
            </button>
          )}
        </div>

        {/* Report Selection Section */}
        <div className="flex flex-col gap-3 p-3 rounded-lg bg-white/50 dark:bg-slate-900/50 border border-purple-200/40 dark:border-purple-700/40 hover:border-purple-300/60 dark:hover:border-purple-600/60 transition-all">
          <div className="flex items-center gap-2">
            <div className="w-4 h-4 rounded-full bg-gradient-to-r from-purple-500 to-pink-500 flex items-center justify-center">
              <span className="text-xs">📊</span>
            </div>
            <span className="text-xs font-bold text-purple-700 dark:text-purple-300 uppercase tracking-widest">نوع التقرير</span>
          </div>
          <Select value={activeReport} onValueChange={setActiveReport}>
            <SelectTrigger className="h-10 text-sm rounded-lg border-2 border-purple-300/60 bg-gradient-to-r from-white to-purple-50 dark:from-slate-800 dark:to-slate-800 hover:border-purple-400/80 focus:ring-2 focus:ring-purple-500/60 focus:ring-offset-2 dark:focus:ring-offset-slate-900 transition-all font-medium">
              <SelectValue placeholder="اختر التقرير" />
            </SelectTrigger>
            <SelectContent className="rounded-lg">
              {reportOptions.map((report) => (
                <SelectItem key={report.value} value={report.value} className="cursor-pointer">
                  <span className="text-sm font-medium">{report.label}</span>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <p className="text-xs text-purple-600/70 dark:text-purple-400/70 font-medium">✨ اختر نوع التقرير المطلوب عرضه</p>
        </div>
      </div>
    </div>
  );

  // ── Render ──────────────────────────────────────────────────────────────────

  return (
    <div className="space-y-4">
      {dateBar}

      <Tabs value={activeReport} onValueChange={setActiveReport}>

        {/* ── 1. Profit by Invoice ──────────────────────────────────────────── */}
        <TabsContent value="profit-invoice" className="space-y-3 mt-4">
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            <MetricCard label="إجمالي المبيعات" value={fmt(profitSummary.totalSales, currencySymbol)} />
            <MetricCard label="التكلفة التقديرية" value={fmt(profitSummary.totalCost, currencySymbol)} />
            <MetricCard label="الربح التقديري" value={fmt(profitSummary.totalProfit, currencySymbol)} />
            <MetricCard label="هامش الربح" value={pct(profitSummary.margin)} />
          </div>
          <ReportTable
            headers={['#', 'رقم الفاتورة', 'التاريخ', 'العميل', 'المبيعات', 'التكلفة', 'الربح', 'الهامش %']}
            rows={profitByInvoice.map((r, i) => [
              i + 1,
              r.invoiceNumber,
              r.date,
              r.customerName,
              fmt(r.salesValue, currencySymbol),
              fmt(r.estimatedCost, currencySymbol),
              <span key="p" className={r.estimatedProfit >= 0 ? 'text-green-700' : 'text-red-600'}>{fmt(r.estimatedProfit, currencySymbol)}</span>,
              <span key="m" className={r.profitMargin >= 0 ? 'text-green-700' : 'text-red-600'}>{pct(r.profitMargin)}</span>,
            ])}
          />
        </TabsContent>

        {/* ── 2. Profit Margin Summary ─────────────────────────────────────── */}
        <TabsContent value="profit-margin" className="space-y-3 mt-4">
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            <MetricCard label="عدد الفواتير" value={profitByInvoice.length.toString()} />
            <MetricCard label="إجمالي المبيعات" value={fmt(profitSummary.totalSales, currencySymbol)} />
            <MetricCard label="إجمالي التكلفة التقديرية" value={fmt(profitSummary.totalCost, currencySymbol)} />
            <MetricCard label="صافي الربح التقديري" value={fmt(profitSummary.totalProfit, currencySymbol)} sub={`هامش: ${pct(profitSummary.margin)}`} />
          </div>
          <ReportTable
            headers={['العميل', 'المبيعات', 'التكلفة', 'الربح', 'الهامش %']}
            rows={(() => {
              const map = new Map<string, { name: string; sales: number; cost: number }>();
              profitByInvoice.forEach((r) => {
                const cur = map.get(r.customerId) ?? { name: r.customerName, sales: 0, cost: 0 };
                cur.sales += r.salesValue;
                cur.cost += r.estimatedCost;
                map.set(r.customerId, cur);
              });
              return Array.from(map.values())
                .sort((a, b) => (b.sales - b.cost) - (a.sales - a.cost))
                .map((row) => {
                  const profit = row.sales - row.cost;
                  const margin = row.sales > 0 ? (profit / row.sales) * 100 : 0;
                  return [
                    row.name,
                    fmt(row.sales, currencySymbol),
                    fmt(row.cost, currencySymbol),
                    <span key="p" className={profit >= 0 ? 'text-green-700' : 'text-red-600'}>{fmt(profit, currencySymbol)}</span>,
                    <span key="m" className={margin >= 0 ? 'text-green-700' : 'text-red-600'}>{pct(margin)}</span>,
                  ];
                });
            })()}
          />
        </TabsContent>

        {/* ── 3. Price vs Cost Variance ────────────────────────────────────── */}
        <TabsContent value="price-variance" className="space-y-3 mt-4">
          <p className="text-sm text-muted-foreground">مقارنة متوسط سعر البيع الفعلي مقابل تكلفة الشراء لكل صنف</p>
          <ReportTable
            headers={['الصنف', 'الكمية المباعة', 'متوسط سعر البيع', 'تكلفة الشراء', 'الفجوة', 'الفجوة %', 'إجمالي الربح']}
            rows={priceVarianceRows.map((r) => [
              r.materialName,
              r.quantitySold.toLocaleString('en-US'),
              fmt(r.avgSellingPrice, currencySymbol),
              fmt(r.purchaseCost, currencySymbol),
              <span key="v" className={r.varianceAmount >= 0 ? 'text-green-700' : 'text-red-600'}>{fmt(r.varianceAmount, currencySymbol)}</span>,
              <span key="vp" className={r.variancePercent >= 0 ? 'text-green-700' : 'text-red-600'}>{pct(r.variancePercent)}</span>,
              fmt(r.totalProfit, currencySymbol),
            ])}
          />
        </TabsContent>

        {/* ── 4. Customer Frequency ────────────────────────────────────────── */}
        <TabsContent value="customer-freq" className="space-y-3 mt-4">
          <ReportTable
            headers={['العميل', 'عدد الفواتير', 'إجمالي المبيعات', 'أول فاتورة', 'آخر فاتورة', 'أيام منذ آخر شراء', 'متوسط الفترة بين الفواتير (يوم)']}
            rows={freqRows.map((r) => [
              r.customerName,
              r.invoiceCount,
              fmt(r.totalSales, currencySymbol),
              r.firstInvoiceDate,
              r.lastInvoiceDate,
              r.daysSinceLastPurchase,
              r.avgDaysBetweenPurchases ?? '—',
            ])}
          />
        </TabsContent>

        {/* ── 5. Inactive Customers ────────────────────────────────────────── */}
        <TabsContent value="inactive" className="space-y-3 mt-4">
          <div className="flex items-center gap-3">
            <label className="text-sm font-medium">عدم النشاط منذ (يوم):</label>
            <input
              type="number"
              value={inactiveThreshold}
              onChange={(e) => setInactiveThreshold(Math.max(1, Number(e.target.value)))}
              className="border rounded px-2 py-1 text-sm w-24 bg-background"
              min={1}
            />
            <span className="text-sm text-muted-foreground">({inactiveRows.length} عميل)</span>
          </div>
          <ReportTable
            headers={['العميل', 'آخر فاتورة', 'أيام منذ آخر شراء', 'إجمالي مشتريات سابقة', 'عدد الفواتير']}
            rows={inactiveRows.map((r) => [
              r.customerName,
              r.lastInvoiceDate,
              <span key="d" className="text-red-600 font-semibold">{r.daysSinceLastPurchase}</span>,
              fmt(r.totalSales, currencySymbol),
              r.invoiceCount,
            ])}
          />
        </TabsContent>

        {/* ── 6. Top Debtors ───────────────────────────────────────────────── */}
        <TabsContent value="top-debtors" className="space-y-3 mt-4">
          <ReportTable
            headers={['#', 'العميل', 'إجمالي المطلوب', 'المدفوع', 'المتبقي', 'أقدم فاتورة غير مسددة']}
            rows={topDebtors.map((r, i) => [
              i + 1,
              r.customerName,
              fmt(r.totalBilled, currencySymbol),
              fmt(r.totalPaid, currencySymbol),
              <span key="d" className="text-red-600 font-bold">{fmt(r.amountDue, currencySymbol)}</span>,
              r.oldestUnpaidDate,
            ])}
          />
        </TabsContent>

        {/* ── 7. Dwell Time ─────────────────────────────────────────────────── */}
        <TabsContent value="dwell-time" className="space-y-3 mt-4">
          <p className="text-sm text-muted-foreground">المدة الزمنية منذ أول حركة للصنف حتى اليوم (الأصناف التي لا تزال في المخزون)</p>
          <ReportTable
            headers={['الصنف', 'أول حركة', 'آخر حركة', 'الأيام في المخزون', 'الكمية الحالية']}
            rows={dwellRows.map((r) => [
              r.materialName,
              r.firstMovementDate,
              r.lastMovementDate,
              <span key="d" className={r.avgDaysInStock > 180 ? 'text-red-600 font-semibold' : r.avgDaysInStock > 90 ? 'text-orange-500' : ''}>{r.avgDaysInStock}</span>,
              r.currentStockQty.toLocaleString('en-US'),
            ])}
          />
        </TabsContent>

        {/* ── 8. Best Selling Time ─────────────────────────────────────────── */}
        <TabsContent value="best-time" className="space-y-3 mt-4">
          <p className="text-sm text-muted-foreground">تحليل المبيعات حسب يوم الأسبوع</p>
          <div className="overflow-x-auto rounded border">
            <table className="w-full text-sm text-right">
              <thead className="bg-muted/60 text-xs font-semibold">
                <tr>
                  <th className="px-3 py-2">يوم الأسبوع</th>
                  <th className="px-3 py-2">عدد الفواتير</th>
                  <th className="px-3 py-2">إجمالي المبيعات</th>
                  <th className="px-3 py-2">متوسط الفاتورة</th>
                  <th className="px-3 py-2">النشاط</th>
                </tr>
              </thead>
              <tbody>
                {(() => {
                  const maxSales = Math.max(...bestTimeRows.map((r) => r.totalSales), 1);
                  return bestTimeRows.map((r, i) => (
                    <tr key={r.dayOfWeek} className={i % 2 === 0 ? 'bg-white dark:bg-background' : 'bg-muted/20'}>
                      <td className="px-3 py-2 font-medium">{r.dayNameAr}</td>
                      <td className="px-3 py-2">{r.invoiceCount}</td>
                      <td className="px-3 py-2">{fmt(r.totalSales, currencySymbol)}</td>
                      <td className="px-3 py-2">{fmt(r.averageSale, currencySymbol)}</td>
                      <td className="px-3 py-2 w-40">
                        <div className="flex items-center gap-2">
                          <div className="bg-blue-200 rounded-full h-2 flex-1">
                            <div
                              className="bg-blue-600 h-2 rounded-full"
                              style={{ width: `${maxSales > 0 ? (r.totalSales / maxSales) * 100 : 0}%` }}
                            />
                          </div>
                        </div>
                      </td>
                    </tr>
                  ));
                })()}
              </tbody>
            </table>
          </div>
        </TabsContent>

        {/* ── 9. Branch / Warehouse Performance ───────────────────────────── */}
        <TabsContent value="branch" className="space-y-3 mt-4">
          <ReportTable
            headers={['المستودع', 'عدد الفواتير', 'عدد السطور', 'الكمية', 'المبيعات', 'التكلفة', 'الربح', 'هامش %']}
            rows={branchRows.map((r) => [
              r.warehouseId,
              r.invoiceCount,
              r.lineCount,
              r.totalQuantity.toLocaleString('en-US'),
              fmt(r.totalSales, currencySymbol),
              fmt(r.estimatedCost, currencySymbol),
              fmt(r.estimatedProfit, currencySymbol),
              pct(r.profitMargin),
            ])}
          />
        </TabsContent>

        {/* ── 10. Category Performance ─────────────────────────────────────── */}
        <TabsContent value="category" className="space-y-3 mt-4">
          <ReportTable
            headers={['الفئة', 'عدد الأصناف المباعة', 'الكمية', 'المبيعات', 'التكلفة', 'الربح', 'هامش %']}
            rows={catRows.map((r) => [
              r.groupName,
              r.lineCount,
              r.totalQuantity.toLocaleString('en-US'),
              fmt(r.totalSales, currencySymbol),
              fmt(r.estimatedCost, currencySymbol),
              fmt(r.estimatedProfit, currencySymbol),
              pct(r.profitMargin),
            ])}
          />
        </TabsContent>

        {/* ── 11. Collection Rate ──────────────────────────────────────────── */}
        <TabsContent value="collection-rate" className="space-y-3 mt-4">
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            <MetricCard label="إجمالي المطلوب" value={fmt(collectionRate.totalBilled, currencySymbol)} />
            <MetricCard label="إجمالي المحصّل" value={fmt(collectionRate.totalPaid, currencySymbol)} />
            <MetricCard label="المتبقي" value={fmt(collectionRate.totalDue, currencySymbol)} />
            <MetricCard label="نسبة التحصيل الكلية" value={pct(collectionRate.overallRate)} />
          </div>
          <ReportTable
            headers={['العميل', 'المطلوب', 'المحصّل', 'المتبقي', 'نسبة التحصيل']}
            rows={collectionRate.rows.map((r) => [
              r.customerName,
              fmt(r.totalBilled, currencySymbol),
              fmt(r.totalPaid, currencySymbol),
              fmt(r.totalDue, currencySymbol),
              <span key="cr" className={r.collectionRate >= 80 ? 'text-green-700' : r.collectionRate >= 50 ? 'text-orange-500' : 'text-red-600'}>
                {pct(r.collectionRate)}
              </span>,
            ])}
          />
        </TabsContent>

        {/* ── 12. DSO ──────────────────────────────────────────────────────── */}
        <TabsContent value="dso" className="space-y-3 mt-4">
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
            <MetricCard label="DSO (أيام المبيعات المعلقة)" value={`${dso.dso} يوم`} sub="= ذمم ÷ مبيعات × أيام الفترة" />
            <MetricCard label="متوسط أيام التحصيل الفعلية" value={`${dso.averageDaysToCollect} يوم`} sub="مبني على تواريخ المدفوعات" />
            <MetricCard label="الذمم الحالية" value={fmt(dso.accountsReceivable, currencySymbol)} />
            <MetricCard label="إجمالي المبيعات" value={fmt(dso.totalSales, currencySymbol)} />
            <MetricCard label="أيام الفترة" value={`${dso.daysPeriod} يوم`} />
          </div>
          <div className="rounded border p-4 bg-muted/20 text-sm space-y-1">
            <p><span className="font-semibold">المعادلة:</span> DSO = (الذمم ÷ المبيعات) × أيام الفترة</p>
            <p className="text-muted-foreground">كلما انخفض DSO، كان التحصيل أسرع وكفاءة السيولة أعلى</p>
          </div>
        </TabsContent>

        {/* ── 13. Discount Analysis ────────────────────────────────────────── */}
        <TabsContent value="discounts" className="space-y-3 mt-4">
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
            <MetricCard label="إجمالي المبيعات قبل الخصم" value={fmt(discountSummary.totalGross, currencySymbol)} />
            <MetricCard label="إجمالي الخصومات" value={fmt(discountSummary.totalDiscount, currencySymbol)} />
            <MetricCard label="صافي المبيعات بعد الخصم" value={fmt(discountSummary.totalNet, currencySymbol)} />
            <MetricCard label="نسبة الخصم الإجمالية" value={pct(discountSummary.overallDiscountRate)} />
            <MetricCard label="فواتير بها خصم" value={`${discountSummary.invoicesWithDiscount} / ${discountSummary.totalInvoices}`} />
          </div>
        </TabsContent>

        {/* ── 14. Daily Performance ────────────────────────────────────────── */}
        <TabsContent value="daily" className="space-y-3 mt-4">
          <div className="flex items-center gap-3 mb-2">
            <label className="text-sm font-medium">التاريخ:</label>
            <input
              type="date"
              value={dailyDate}
              onChange={(e) => setDailyDate(e.target.value)}
              className="border rounded px-2 py-1 text-sm bg-background"
            />
          </div>
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            <MetricCard label="عدد الفواتير" value={dailyPerf.invoiceCount.toString()} />
            <MetricCard label="إجمالي المبيعات" value={fmt(dailyPerf.totalSales, currencySymbol)} />
            <MetricCard label="المرتجعات" value={`${dailyPerf.returnCount} (${fmt(dailyPerf.totalReturns, currencySymbol)})`} />
            <MetricCard label="صافي المبيعات" value={fmt(dailyPerf.netSales, currencySymbol)} />
            <MetricCard label="المبالغ المحصّلة" value={fmt(dailyPerf.totalPaymentsReceived, currencySymbol)} />
          </div>
        </TabsContent>

        {/* ── 15. Period Comparison ────────────────────────────────────────── */}
        <TabsContent value="period-compare" className="space-y-4 mt-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div className="border rounded p-3 space-y-2">
              <p className="font-semibold text-sm">الفترة الأولى</p>
              <div className="flex gap-2 flex-wrap">
                <label className="flex items-center gap-1 text-xs">
                  من <input type="date" value={p1From} onChange={(e) => setP1From(e.target.value)} className="border rounded px-2 py-1 bg-background" />
                </label>
                <label className="flex items-center gap-1 text-xs">
                  إلى <input type="date" value={p1To} onChange={(e) => setP1To(e.target.value)} className="border rounded px-2 py-1 bg-background" />
                </label>
              </div>
            </div>
            <div className="border rounded p-3 space-y-2">
              <p className="font-semibold text-sm">الفترة الثانية</p>
              <div className="flex gap-2 flex-wrap">
                <label className="flex items-center gap-1 text-xs">
                  من <input type="date" value={p2From} onChange={(e) => setP2From(e.target.value)} className="border rounded px-2 py-1 bg-background" />
                </label>
                <label className="flex items-center gap-1 text-xs">
                  إلى <input type="date" value={p2To} onChange={(e) => setP2To(e.target.value)} className="border rounded px-2 py-1 bg-background" />
                </label>
              </div>
            </div>
          </div>
          {!periodComp ? (
            <p className="text-sm text-muted-foreground text-center py-6">حدد الفترتين لعرض المقارنة</p>
          ) : (
            <div className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div className="border rounded p-4 space-y-3">
                  <p className="font-semibold text-sm border-b pb-1">
                    {periodComp.period1.fromDate} → {periodComp.period1.toDate}
                  </p>
                  <div className="space-y-1 text-sm">
                    <div className="flex justify-between"><span>عدد الفواتير</span><span className="font-bold">{periodComp.period1.invoiceCount}</span></div>
                    <div className="flex justify-between"><span>إجمالي المبيعات</span><span className="font-bold">{fmt(periodComp.period1.totalSales, currencySymbol)}</span></div>
                    <div className="flex justify-between"><span>متوسط الفاتورة</span><span className="font-bold">{fmt(periodComp.period1.averageInvoice, currencySymbol)}</span></div>
                  </div>
                </div>
                <div className="border rounded p-4 space-y-3">
                  <p className="font-semibold text-sm border-b pb-1">
                    {periodComp.period2.fromDate} → {periodComp.period2.toDate}
                  </p>
                  <div className="space-y-1 text-sm">
                    <div className="flex justify-between"><span>عدد الفواتير</span><span className="font-bold">{periodComp.period2.invoiceCount}</span></div>
                    <div className="flex justify-between"><span>إجمالي المبيعات</span><span className="font-bold">{fmt(periodComp.period2.totalSales, currencySymbol)}</span></div>
                    <div className="flex justify-between"><span>متوسط الفاتورة</span><span className="font-bold">{fmt(periodComp.period2.averageInvoice, currencySymbol)}</span></div>
                  </div>
                </div>
                <div className="border rounded p-4 bg-muted/20 space-y-3">
                  <p className="font-semibold text-sm border-b pb-1">نمو الفترة 2 مقابل 1</p>
                  <div className="space-y-2 text-sm">
                    <div className="flex justify-between items-center"><span>المبيعات</span>{growthBadge(periodComp.growthSales)}</div>
                    <div className="flex justify-between items-center"><span>عدد الفواتير</span>{growthBadge(periodComp.growthInvoiceCount)}</div>
                    <div className="flex justify-between items-center"><span>متوسط الفاتورة</span>{growthBadge(periodComp.growthAvgInvoice)}</div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </TabsContent>

        {/* ── 16. Revenue vs Expenses ──────────────────────────────────────── */}
        <TabsContent value="rev-vs-exp" className="space-y-3 mt-4">
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
            <MetricCard label="إجمالي الإيرادات" value={fmt(revVsExp.totalRevenue, currencySymbol)} />
            <MetricCard label="إجمالي المصاريف" value={fmt(revVsExp.totalExpenses, currencySymbol)} />
            <MetricCard
              label="صافي الدخل"
              value={fmt(revVsExp.netIncome, currencySymbol)}
              sub={revVsExp.netIncome >= 0 ? 'ربح' : 'خسارة'}
            />
          </div>
          <ReportTable
            headers={['رمز الحساب', 'اسم الحساب', 'النوع', 'المبلغ']}
            rows={revVsExp.rows.map((r) => [
              r.accountCode,
              r.accountName,
              <span key="t" className={r.accountType === 'revenue' ? 'text-green-700 font-medium' : 'text-red-600 font-medium'}>
                {r.accountType === 'revenue' ? 'إيراد' : 'مصروف'}
              </span>,
              fmt(r.totalAmount, currencySymbol),
            ])}
          />
        </TabsContent>
      </Tabs>
    </div>
  );
}
