'use client';

import { useMemo, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { formatCurrency } from '@/lib/currency-formatter';
import type { Customer, SalesInvoice, SalesRep, Supplier, PurchaseOrder, InventoryMovement, CustomerPayment, JournalEntry } from '@/lib/types';
import {
  type PosShiftSessionLike,
  type ReportFilters,
  buildAgingReport,
  buildCollectionMonitoring,
  buildCurrentStock,
  buildCustomerProfitability,
  buildInventoryCostReport,
  buildInventoryTurnover,
  buildItemMovementReport,
  buildOpenInvoices,
  buildPurchaseBySupplier,
  buildPurchaseSummary,
  buildReorderReport,
  buildReturnsReport,
  buildPosShiftReport,
  buildSalesByItem,
  buildSalesRepPerformance,
  buildSalesSummary,
  buildStaleItemsReport,
  buildTopSellingItems,
} from '@/lib/reports/operational-reporting';

type MaterialLite = {
  id: string;
  name: string;
  purchasePrice?: number;
  reorderMinimumQty?: number;
};

type Props = {
  invoices: SalesInvoice[];
  purchaseOrders: PurchaseOrder[];
  inventoryMovements: InventoryMovement[];
  payments: CustomerPayment[];
  journalEntries: JournalEntry[];
  customers: Customer[];
  suppliers: Supplier[];
  salesReps: SalesRep[];
  materials: MaterialLite[];
  posShiftSessions: PosShiftSessionLike[];
  currencySymbol: string;
  defaultDate: string;
  initialTab?: string;
};

function StatCard({ title, value, className = '' }: { title: string; value: string | number; className?: string }) {
  return (
    <div className="rounded-md border p-4">
      <p className="text-xs text-muted-foreground">{title}</p>
      <p className={`text-xl font-bold ${className}`}>{value}</p>
    </div>
  );
}

export default function OperationalReportsClient({
  invoices,
  purchaseOrders,
  inventoryMovements,
  payments,
  journalEntries,
  customers,
  suppliers,
  salesReps,
  materials,
  posShiftSessions,
  currencySymbol,
  defaultDate,
  initialTab,
}: Props) {
  const fmt = (value: number) => formatCurrency(Number(value || 0), currencySymbol);

  const [fromDate, setFromDate] = useState('');
  const [toDate, setToDate] = useState(defaultDate);
  const [reportTab, setReportTab] = useState(initialTab || 'sales-total');
  const [customerId, setCustomerId] = useState('all');
  const [supplierId, setSupplierId] = useState('all');
  const [salesRepId, setSalesRepId] = useState('all');
  const [posShiftUserId, setPosShiftUserId] = useState('all');
  const [materialId, setMaterialId] = useState('all');

  const [topSortBy, setTopSortBy] = useState<'quantity' | 'value'>('value');
  const [staleDays, setStaleDays] = useState('60');
  const [collectionCustomerFilter, setCollectionCustomerFilter] = useState('');
  const [collectionMinRemainingFilter, setCollectionMinRemainingFilter] = useState('');
  const [collectionLastPaymentFromFilter, setCollectionLastPaymentFromFilter] = useState('');
  const [collectionLastPaymentToFilter, setCollectionLastPaymentToFilter] = useState('');
  const [collectionDaysSinceMinFilter, setCollectionDaysSinceMinFilter] = useState('');

  const reportOptions = [
    { value: 'sales-total', label: 'المبيعات الإجمالية' },
    { value: 'sales-by-item', label: 'المبيعات حسب الصنف' },
    { value: 'top-selling', label: 'الأصناف الأكثر مبيعًا' },
    { value: 'stale-items', label: 'الأصناف الراكدة' },
    { value: 'current-stock', label: 'المخزون الحالي' },
    { value: 'item-movement', label: 'حركة صنف' },
    { value: 'inventory-cost', label: 'تكلفة المخزون' },
    { value: 'purchases', label: 'المشتريات' },
    { value: 'purchase-by-supplier', label: 'المشتريات حسب المورد' },
    { value: 'aging', label: 'تعمير الذمم' },
    { value: 'collection', label: 'مراقبة التحصيل' },
    { value: 'open-invoices', label: 'الفواتير المفتوحة' },
    { value: 'profit-by-item', label: 'ربحية حسب الصنف' },
    { value: 'profit-by-customer', label: 'ربحية حسب العميل' },
    { value: 'rep-performance', label: 'أداء المندوبين' },
    { value: 'turnover', label: 'دوران المخزون' },
    { value: 'reorder', label: 'حد إعادة الطلب' },
    { value: 'returns', label: 'المرتجعات' },
    { value: 'pos-shifts', label: 'ورديات نقاط البيع' },
  ] as const;

  const filters: ReportFilters = useMemo(() => ({
    fromDate,
    toDate,
    customerId: customerId === 'all' ? undefined : customerId,
    supplierId: supplierId === 'all' ? undefined : supplierId,
    salesRepId: salesRepId === 'all' ? undefined : salesRepId,
    materialId: materialId === 'all' ? undefined : materialId,
  }), [fromDate, toDate, customerId, supplierId, salesRepId, materialId]);

  const salesSummary = useMemo(() => buildSalesSummary(invoices, filters), [invoices, filters]);
  const salesByItem = useMemo(() => buildSalesByItem(invoices, materials, filters), [invoices, materials, filters]);
  const topSelling = useMemo(() => buildTopSellingItems(salesByItem, topSortBy, 10), [salesByItem, topSortBy]);
  const staleItems = useMemo(() => buildStaleItemsReport(inventoryMovements, materials, Math.max(1, Number(staleDays || 60))), [inventoryMovements, materials, staleDays]);

  const currentStock = useMemo(() => buildCurrentStock(inventoryMovements, materials, filters), [inventoryMovements, materials, filters]);
  const itemMovement = useMemo(() => buildItemMovementReport(inventoryMovements, materialId === 'all' ? '' : materialId, filters), [inventoryMovements, materialId, filters]);
  const inventoryCost = useMemo(() => buildInventoryCostReport(inventoryMovements, materials, filters), [inventoryMovements, materials, filters]);

  const purchaseSummary = useMemo(() => buildPurchaseSummary(purchaseOrders, filters), [purchaseOrders, filters]);
  const purchaseBySupplier = useMemo(() => buildPurchaseBySupplier(purchaseOrders, filters), [purchaseOrders, filters]);

  const aging = useMemo(() => buildAgingReport(journalEntries, customers, suppliers, toDate), [journalEntries, customers, suppliers, toDate]);
  const collection = useMemo(() => buildCollectionMonitoring(invoices, payments, filters), [invoices, payments, filters]);
  const filteredCollection = useMemo(() => {
    const query = collectionCustomerFilter.trim().toLowerCase();
    const minRemaining = Number(collectionMinRemainingFilter || 0);
    const daysMin = Number(collectionDaysSinceMinFilter || 0);

    return collection.filter((row) => {
      if (query && !String(row.customerName || '').toLowerCase().includes(query)) return false;
      if (collectionMinRemainingFilter && Number.isFinite(minRemaining) && row.remaining < minRemaining) return false;

      const lastPaymentDate = String(row.lastPaymentDate || '');
      if (collectionLastPaymentFromFilter) {
        if (!lastPaymentDate || lastPaymentDate < collectionLastPaymentFromFilter) return false;
      }
      if (collectionLastPaymentToFilter) {
        if (!lastPaymentDate || lastPaymentDate > collectionLastPaymentToFilter) return false;
      }

      if (collectionDaysSinceMinFilter) {
        if (!Number.isFinite(daysMin)) return false;
        if (row.daysSinceLastPayment === null || row.daysSinceLastPayment < daysMin) return false;
      }

      return true;
    });
  }, [
    collection,
    collectionCustomerFilter,
    collectionMinRemainingFilter,
    collectionLastPaymentFromFilter,
    collectionLastPaymentToFilter,
    collectionDaysSinceMinFilter,
  ]);
  const openInvoices = useMemo(() => buildOpenInvoices(invoices, filters), [invoices, filters]);

  const itemProfitability = useMemo(() => salesByItem, [salesByItem]);
  const customerProfitability = useMemo(() => buildCustomerProfitability(invoices, materials, filters), [invoices, materials, filters]);
  const repPerformance = useMemo(() => buildSalesRepPerformance(invoices, salesReps, filters), [invoices, salesReps, filters]);
  const turnover = useMemo(() => buildInventoryTurnover(invoices, materials, inventoryMovements, filters), [invoices, materials, inventoryMovements, filters]);
  const reorder = useMemo(() => buildReorderReport(inventoryMovements, materials, filters), [inventoryMovements, materials, filters]);
  const returns = useMemo(() => buildReturnsReport(invoices, filters), [invoices, filters]);
  const posShiftUsers = useMemo(() => {
    const map = new Map<string, string>();
    (posShiftSessions || []).forEach((session) => {
      const id = String(session?.userId || '').trim();
      if (!id) return;
      const name = String(session?.userName || '').trim() || id;
      if (!map.has(id)) map.set(id, name);
    });
    return Array.from(map.entries()).map(([id, name]) => ({ id, name }));
  }, [posShiftSessions]);
  const posShiftsReport = useMemo(() => buildPosShiftReport(
    posShiftSessions,
    { fromDate, toDate },
    posShiftUserId === 'all' ? undefined : posShiftUserId,
  ), [posShiftSessions, fromDate, toDate, posShiftUserId]);
  const transferredPosShiftSessions = useMemo(
    () => posShiftsReport.sessions.filter((row) => row.status === 'closed' && !row.requiresApproval && row.cashVarianceHandled),
    [posShiftsReport.sessions],
  );

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle>فلاتر التقارير التشغيلية</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid gap-3 md:grid-cols-8">
            <Input type="date" value={fromDate} onChange={(event) => setFromDate(event.target.value)} />
            <Input type="date" value={toDate} onChange={(event) => setToDate(event.target.value)} />
            <Select value={customerId} onValueChange={setCustomerId}>
              <SelectTrigger><SelectValue placeholder="عميل" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">كل العملاء</SelectItem>
                {customers.map((customer) => (
                  <SelectItem key={customer.id} value={customer.id}>{customer.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={salesRepId} onValueChange={setSalesRepId}>
              <SelectTrigger><SelectValue placeholder="مندوب" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">كل المندوبين</SelectItem>
                {salesReps.map((rep) => (
                  <SelectItem key={rep.id} value={rep.id}>{rep.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={supplierId} onValueChange={setSupplierId}>
              <SelectTrigger><SelectValue placeholder="مورد" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">كل الموردين</SelectItem>
                {suppliers.map((supplier) => (
                  <SelectItem key={supplier.id} value={supplier.id}>{supplier.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={posShiftUserId} onValueChange={setPosShiftUserId}>
              <SelectTrigger><SelectValue placeholder="مستخدم نقطة البيع" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">كل المستخدمين</SelectItem>
                {posShiftUsers.map((user) => (
                  <SelectItem key={user.id} value={user.id}>{user.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={materialId} onValueChange={setMaterialId}>
              <SelectTrigger><SelectValue placeholder="صنف" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">كل الأصناف</SelectItem>
                {materials.map((material) => (
                  <SelectItem key={material.id} value={material.id}>{material.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <div className="flex items-center rounded-md border px-3 text-xs text-muted-foreground">الفلاتر تطبق على أغلب التقارير</div>
          </div>

          <div className="mt-3 grid gap-3 md:grid-cols-8">
            <div className="md:col-span-3">
              <p className="mb-2 text-xs font-medium text-muted-foreground">اختر التقرير</p>
              <Select value={reportTab} onValueChange={setReportTab}>
                <SelectTrigger>
                  <SelectValue placeholder="اختر التقرير" />
                </SelectTrigger>
                <SelectContent>
                  {reportOptions.map((report) => (
                    <SelectItem key={report.value} value={report.value}>{report.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      <Tabs value={reportTab} onValueChange={setReportTab} className="space-y-4">

        <TabsContent value="sales-total">
          <Card>
            <CardContent className="space-y-4 pt-6">
              <div className="grid gap-4 md:grid-cols-4">
                <StatCard title="عدد فواتير البيع" value={salesSummary.invoiceCount} />
                <StatCard title="إجمالي المبيعات" value={fmt(salesSummary.totalSales)} className="text-emerald-700" />
                <StatCard title="المدفوع" value={fmt(salesSummary.totalPaid)} className="text-sky-700" />
                <StatCard title="المتبقي" value={fmt(salesSummary.totalDue)} className="text-rose-700" />
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="sales-by-item">
          <Card>
            <CardContent className="pt-6">
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>الصنف</TableHead>
                      <TableHead className="text-right">الكمية</TableHead>
                      <TableHead className="text-right">قيمة المبيعات</TableHead>
                      <TableHead className="text-right">التكلفة التقديرية</TableHead>
                      <TableHead className="text-right">الربح التقديري</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {salesByItem.length === 0 ? <TableRow><TableCell colSpan={5} className="py-8 text-center text-muted-foreground">لا توجد بيانات.</TableCell></TableRow> : salesByItem.map((row) => (
                      <TableRow key={row.materialId}>
                        <TableCell>{row.materialName}</TableCell>
                        <TableCell className="text-right">{row.quantitySold}</TableCell>
                        <TableCell className="text-right">{fmt(row.salesValue)}</TableCell>
                        <TableCell className="text-right">{fmt(row.estimatedCost)}</TableCell>
                        <TableCell className="text-right">{fmt(row.estimatedProfit)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="top-selling">
          <Card>
            <CardContent className="space-y-4 pt-6">
              <div className="max-w-xs">
                <Select value={topSortBy} onValueChange={(value) => setTopSortBy(value as 'quantity' | 'value')}>
                  <SelectTrigger><SelectValue placeholder="ترتيب حسب" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="value">القيمة</SelectItem>
                    <SelectItem value="quantity">الكمية</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>الصنف</TableHead>
                      <TableHead className="text-right">الكمية</TableHead>
                      <TableHead className="text-right">القيمة</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {topSelling.length === 0 ? <TableRow><TableCell colSpan={3} className="py-8 text-center text-muted-foreground">لا توجد بيانات.</TableCell></TableRow> : topSelling.map((row) => (
                      <TableRow key={row.materialId}>
                        <TableCell>{row.materialName}</TableCell>
                        <TableCell className="text-right">{row.quantitySold}</TableCell>
                        <TableCell className="text-right">{fmt(row.salesValue)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="stale-items">
          <Card>
            <CardContent className="space-y-4 pt-6">
              <div className="max-w-xs">
                <Input type="number" min={1} value={staleDays} onChange={(event) => setStaleDays(event.target.value)} placeholder="عدد الأيام" />
              </div>
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>الصنف</TableHead>
                      <TableHead className="text-right">آخر حركة</TableHead>
                      <TableHead className="text-right">منذ (يوم)</TableHead>
                      <TableHead className="text-right">الرصيد الحالي</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {staleItems.length === 0 ? <TableRow><TableCell colSpan={4} className="py-8 text-center text-muted-foreground">لا توجد أصناف راكدة حسب الإعداد.</TableCell></TableRow> : staleItems.map((row) => (
                      <TableRow key={row.materialId}>
                        <TableCell>{row.materialName}</TableCell>
                        <TableCell className="text-right">{row.lastMovementDate || '-'}</TableCell>
                        <TableCell className="text-right">{row.daysSinceLastMove}</TableCell>
                        <TableCell className="text-right">{row.currentStockQty}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="current-stock">
          <Card>
            <CardContent className="pt-6">
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>الصنف</TableHead>
                      <TableHead className="text-right">وارد</TableHead>
                      <TableHead className="text-right">صادر</TableHead>
                      <TableHead className="text-right">الرصيد</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {currentStock.length === 0 ? <TableRow><TableCell colSpan={4} className="py-8 text-center text-muted-foreground">لا توجد بيانات مخزون.</TableCell></TableRow> : currentStock.map((row) => (
                      <TableRow key={row.materialId}>
                        <TableCell>{row.materialName}</TableCell>
                        <TableCell className="text-right">{row.quantityIn}</TableCell>
                        <TableCell className="text-right">{row.quantityOut}</TableCell>
                        <TableCell className="text-right">{row.balanceQty}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="item-movement">
          <Card>
            <CardContent className="space-y-4 pt-6">
              <div className="text-sm text-muted-foreground">اختر صنفًا من الفلتر العام لعرض الحركة التفصيلية.</div>
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>التاريخ</TableHead>
                      <TableHead>المرجع</TableHead>
                      <TableHead className="text-right">وارد</TableHead>
                      <TableHead className="text-right">صادر</TableHead>
                      <TableHead className="text-right">الصافي</TableHead>
                      <TableHead className="text-right">الرصيد التراكمي</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {itemMovement.length === 0 ? <TableRow><TableCell colSpan={6} className="py-8 text-center text-muted-foreground">لا توجد حركة للصنف المحدد.</TableCell></TableRow> : itemMovement.map((row) => (
                      <TableRow key={row.movementId}>
                        <TableCell>{row.date}</TableCell>
                        <TableCell>{row.referenceType} / {row.referenceId}</TableCell>
                        <TableCell className="text-right">{row.quantityIn}</TableCell>
                        <TableCell className="text-right">{row.quantityOut}</TableCell>
                        <TableCell className="text-right">{row.delta}</TableCell>
                        <TableCell className="text-right">{row.runningQty}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="inventory-cost">
          <Card>
            <CardContent className="space-y-4 pt-6">
              <div className="grid gap-4 md:grid-cols-3">
                <StatCard title="إجمالي قيمة المخزون" value={fmt(inventoryCost.reduce((sum, row) => sum + row.stockValue, 0))} className="text-emerald-700" />
                <StatCard title="عدد الأصناف" value={inventoryCost.length} />
                <StatCard title="إجمالي الكمية" value={inventoryCost.reduce((sum, row) => sum + row.stockQty, 0)} />
              </div>
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>الصنف</TableHead>
                      <TableHead className="text-right">الكمية</TableHead>
                      <TableHead className="text-right">تكلفة الوحدة</TableHead>
                      <TableHead className="text-right">القيمة</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {inventoryCost.length === 0 ? <TableRow><TableCell colSpan={4} className="py-8 text-center text-muted-foreground">لا توجد بيانات.</TableCell></TableRow> : inventoryCost.map((row) => (
                      <TableRow key={row.materialId}>
                        <TableCell>{row.materialName}</TableCell>
                        <TableCell className="text-right">{row.stockQty}</TableCell>
                        <TableCell className="text-right">{fmt(row.unitCost)}</TableCell>
                        <TableCell className="text-right">{fmt(row.stockValue)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="purchases">
          <Card>
            <CardContent className="space-y-4 pt-6">
              <div className="grid gap-4 md:grid-cols-4">
                <StatCard title="عدد فواتير/سندات الشراء" value={purchaseSummary.invoiceCount} />
                <StatCard title="إجمالي المشتريات" value={fmt(purchaseSummary.totalPurchases)} className="text-emerald-700" />
                <StatCard title="المدفوع" value={fmt(purchaseSummary.totalPaid)} className="text-sky-700" />
                <StatCard title="المتبقي" value={fmt(purchaseSummary.totalDue)} className="text-rose-700" />
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="purchase-by-supplier">
          <Card>
            <CardContent className="pt-6">
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>المورد</TableHead>
                      <TableHead className="text-right">عدد السطور</TableHead>
                      <TableHead className="text-right">إجمالي الكمية</TableHead>
                      <TableHead className="text-right">إجمالي القيمة</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {purchaseBySupplier.length === 0 ? <TableRow><TableCell colSpan={4} className="py-8 text-center text-muted-foreground">لا توجد بيانات.</TableCell></TableRow> : purchaseBySupplier.map((row) => (
                      <TableRow key={row.supplierId}>
                        <TableCell>{row.supplierName}</TableCell>
                        <TableCell className="text-right">{row.lineCount}</TableCell>
                        <TableCell className="text-right">{row.totalQuantity}</TableCell>
                        <TableCell className="text-right">{fmt(row.totalValue)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="aging">
          <Card>
            <CardContent className="pt-6">
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>الطرف</TableHead>
                      <TableHead>النوع</TableHead>
                      <TableHead className="text-right">0-30</TableHead>
                      <TableHead className="text-right">31-60</TableHead>
                      <TableHead className="text-right">61-90</TableHead>
                      <TableHead className="text-right">90+</TableHead>
                      <TableHead className="text-right">الإجمالي</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {aging.length === 0 ? <TableRow><TableCell colSpan={7} className="py-8 text-center text-muted-foreground">لا توجد بيانات تعمير.</TableCell></TableRow> : aging.map((row) => (
                      <TableRow key={`${row.partyType}-${row.partyId}`}>
                        <TableCell>{row.partyName}</TableCell>
                        <TableCell>{row.partyType === 'customer' ? 'عميل' : 'مورد'}</TableCell>
                        <TableCell className="text-right">{fmt(row.bucket0to30)}</TableCell>
                        <TableCell className="text-right">{fmt(row.bucket31to60)}</TableCell>
                        <TableCell className="text-right">{fmt(row.bucket61to90)}</TableCell>
                        <TableCell className="text-right">{fmt(row.bucket90plus)}</TableCell>
                        <TableCell className="text-right">{fmt(row.total)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="collection">
          <Card>
            <CardContent className="pt-6">
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>العميل</TableHead>
                      <TableHead className="text-right">إجمالي المستحق</TableHead>
                      <TableHead className="text-right">المدفوع</TableHead>
                      <TableHead className="text-right">المتبقي</TableHead>
                      <TableHead>تاريخ آخر دفعة</TableHead>
                      <TableHead className="text-right">قيمة آخر دفعة</TableHead>
                      <TableHead className="text-right">مضى على آخر دفعة (يوم)</TableHead>
                    </TableRow>
                    <TableRow>
                      <TableHead>
                        <Input
                          value={collectionCustomerFilter}
                          onChange={(event) => setCollectionCustomerFilter(event.target.value)}
                          placeholder="فلترة العميل"
                          className="h-8 text-xs"
                        />
                      </TableHead>
                      <TableHead className="text-right" />
                      <TableHead className="text-right" />
                      <TableHead>
                        <Input
                          type="number"
                          min={0}
                          value={collectionMinRemainingFilter}
                          onChange={(event) => setCollectionMinRemainingFilter(event.target.value)}
                          placeholder="المتبقي >="
                          className="h-8 text-xs"
                        />
                      </TableHead>
                      <TableHead>
                        <Input
                          type="date"
                          value={collectionLastPaymentFromFilter}
                          onChange={(event) => setCollectionLastPaymentFromFilter(event.target.value)}
                          className="h-8 text-xs"
                        />
                      </TableHead>
                      <TableHead>
                        <Input
                          type="date"
                          value={collectionLastPaymentToFilter}
                          onChange={(event) => setCollectionLastPaymentToFilter(event.target.value)}
                          className="h-8 text-xs"
                        />
                      </TableHead>
                      <TableHead>
                        <Input
                          type="number"
                          min={0}
                          value={collectionDaysSinceMinFilter}
                          onChange={(event) => setCollectionDaysSinceMinFilter(event.target.value)}
                          placeholder="الأيام >="
                          className="h-8 text-xs"
                        />
                      </TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredCollection.length === 0 ? <TableRow><TableCell colSpan={7} className="py-8 text-center text-muted-foreground">لا توجد بيانات مطابقة للفلاتر.</TableCell></TableRow> : filteredCollection.map((row) => (
                      <TableRow key={row.customerId}>
                        <TableCell>{row.customerName}</TableCell>
                        <TableCell className="text-right">{fmt(row.totalBilled)}</TableCell>
                        <TableCell className="text-right">{fmt(row.totalPaid)}</TableCell>
                        <TableCell className="text-right">{fmt(row.remaining)}</TableCell>
                        <TableCell>{row.lastPaymentDate || '-'}</TableCell>
                        <TableCell className="text-right">{row.lastPaymentAmount > 0 ? fmt(row.lastPaymentAmount) : '-'}</TableCell>
                        <TableCell className="text-right">{row.daysSinceLastPayment === null ? '-' : row.daysSinceLastPayment}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="open-invoices">
          <Card>
            <CardContent className="pt-6">
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>رقم الفاتورة</TableHead>
                      <TableHead>التاريخ</TableHead>
                      <TableHead>العميل</TableHead>
                      <TableHead className="text-right">الإجمالي</TableHead>
                      <TableHead className="text-right">المدفوع</TableHead>
                      <TableHead className="text-right">المتبقي</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {openInvoices.length === 0 ? <TableRow><TableCell colSpan={6} className="py-8 text-center text-muted-foreground">لا توجد فواتير مفتوحة.</TableCell></TableRow> : openInvoices.map((row) => (
                      <TableRow key={row.invoiceId}>
                        <TableCell>{row.invoiceNumber}</TableCell>
                        <TableCell>{row.date}</TableCell>
                        <TableCell>{row.customerName}</TableCell>
                        <TableCell className="text-right">{fmt(row.grandTotal)}</TableCell>
                        <TableCell className="text-right">{fmt(row.amountPaid)}</TableCell>
                        <TableCell className="text-right">{fmt(row.amountDue)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="profit-by-item">
          <Card>
            <CardContent className="pt-6">
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>الصنف</TableHead>
                      <TableHead className="text-right">المبيعات</TableHead>
                      <TableHead className="text-right">التكلفة التقديرية</TableHead>
                      <TableHead className="text-right">الربح</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {itemProfitability.length === 0 ? <TableRow><TableCell colSpan={4} className="py-8 text-center text-muted-foreground">لا توجد بيانات.</TableCell></TableRow> : itemProfitability.map((row) => (
                      <TableRow key={row.materialId}>
                        <TableCell>{row.materialName}</TableCell>
                        <TableCell className="text-right">{fmt(row.salesValue)}</TableCell>
                        <TableCell className="text-right">{fmt(row.estimatedCost)}</TableCell>
                        <TableCell className="text-right">{fmt(row.estimatedProfit)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="profit-by-customer">
          <Card>
            <CardContent className="pt-6">
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>العميل</TableHead>
                      <TableHead className="text-right">المبيعات</TableHead>
                      <TableHead className="text-right">التكلفة</TableHead>
                      <TableHead className="text-right">الربح</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {customerProfitability.length === 0 ? <TableRow><TableCell colSpan={4} className="py-8 text-center text-muted-foreground">لا توجد بيانات.</TableCell></TableRow> : customerProfitability.map((row) => (
                      <TableRow key={row.customerId}>
                        <TableCell>{row.customerName}</TableCell>
                        <TableCell className="text-right">{fmt(row.salesValue)}</TableCell>
                        <TableCell className="text-right">{fmt(row.estimatedCost)}</TableCell>
                        <TableCell className="text-right">{fmt(row.estimatedProfit)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="rep-performance">
          <Card>
            <CardContent className="pt-6">
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>المندوب</TableHead>
                      <TableHead className="text-right">عدد الفواتير</TableHead>
                      <TableHead className="text-right">المبيعات</TableHead>
                      <TableHead className="text-right">متوسط الفاتورة</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {repPerformance.length === 0 ? <TableRow><TableCell colSpan={4} className="py-8 text-center text-muted-foreground">لا توجد بيانات.</TableCell></TableRow> : repPerformance.map((row) => (
                      <TableRow key={row.salesRepId}>
                        <TableCell>{row.salesRepName}</TableCell>
                        <TableCell className="text-right">{row.invoiceCount}</TableCell>
                        <TableCell className="text-right">{fmt(row.totalSales)}</TableCell>
                        <TableCell className="text-right">{fmt(row.averageInvoice)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="turnover">
          <Card>
            <CardContent className="space-y-4 pt-6">
              <div className="grid gap-4 md:grid-cols-5">
                <StatCard title="تكلفة المبيعات التقديرية" value={fmt(turnover.cogsEstimate)} />
                <StatCard title="مخزون افتتاحي" value={fmt(turnover.openingStockValue)} />
                <StatCard title="مخزون ختامي" value={fmt(turnover.closingStockValue)} />
                <StatCard title="متوسط المخزون" value={fmt(turnover.averageStockValue)} />
                <StatCard title="معدل الدوران" value={turnover.turnoverRate.toFixed(2)} className="text-emerald-700" />
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="reorder">
          <Card>
            <CardContent className="pt-6">
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>الصنف</TableHead>
                      <TableHead className="text-right">الرصيد الحالي</TableHead>
                      <TableHead className="text-right">الحد الأدنى</TableHead>
                      <TableHead className="text-right">العجز</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {reorder.length === 0 ? <TableRow><TableCell colSpan={4} className="py-8 text-center text-muted-foreground">لا توجد أصناف تحت حد إعادة الطلب.</TableCell></TableRow> : reorder.map((row) => (
                      <TableRow key={row.materialId}>
                        <TableCell>{row.materialName}</TableCell>
                        <TableCell className="text-right">{row.currentQty}</TableCell>
                        <TableCell className="text-right">{row.reorderMinimumQty}</TableCell>
                        <TableCell className="text-right">{row.shortageQty}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="returns">
          <Card>
            <CardContent className="pt-6">
              <div className="grid gap-4 md:grid-cols-3">
                <StatCard title="عدد فواتير المرتجع" value={returns.length} />
                <StatCard title="إجمالي قيمة المرتجع" value={fmt(returns.reduce((sum, row) => sum + row.returnValue, 0))} className="text-rose-700" />
                <StatCard title="متوسط قيمة المرتجع" value={fmt(returns.length ? (returns.reduce((sum, row) => sum + row.returnValue, 0) / returns.length) : 0)} />
              </div>
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>الفاتورة</TableHead>
                      <TableHead>التاريخ</TableHead>
                      <TableHead>العميل</TableHead>
                      <TableHead className="text-right">القيمة</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {returns.length === 0 ? <TableRow><TableCell colSpan={4} className="py-8 text-center text-muted-foreground">لا توجد مرتجعات.</TableCell></TableRow> : returns.map((row) => (
                      <TableRow key={row.invoiceId}>
                        <TableCell>{row.invoiceNumber}</TableCell>
                        <TableCell>{row.date}</TableCell>
                        <TableCell>{row.customerName}</TableCell>
                        <TableCell className="text-right">{fmt(row.returnValue)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="pos-shifts">
          <Card>
            <CardContent className="space-y-4 pt-6">
              <div className="grid gap-4 md:grid-cols-5">
                <StatCard title="عدد الورديات" value={posShiftsReport.totals.shiftsCount} />
                <StatCard title="ورديات نشطة" value={posShiftsReport.totals.activeShiftsCount} className="text-sky-700" />
                <StatCard title="ورديات مغلقة" value={posShiftsReport.totals.closedShiftsCount} />
                <StatCard title="إجمالي المبيعات" value={fmt(posShiftsReport.totals.totalSalesAmount)} className="text-emerald-700" />
                <StatCard title="صافي فرق الخزنة" value={fmt(posShiftsReport.totals.cashVariance + posShiftsReport.totals.visaVariance)} className="text-amber-700" />
              </div>

              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>المستخدم</TableHead>
                      <TableHead className="text-right">الورديات</TableHead>
                      <TableHead className="text-right">النشطة</TableHead>
                      <TableHead className="text-right">المغلقة</TableHead>
                      <TableHead className="text-right">الفواتير</TableHead>
                      <TableHead className="text-right">المرتجعات</TableHead>
                      <TableHead className="text-right">المبيعات</TableHead>
                      <TableHead className="text-right">فرق النقد</TableHead>
                      <TableHead className="text-right">فرق البطاقة</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {posShiftsReport.summaryByUser.length === 0 ? <TableRow><TableCell colSpan={9} className="py-8 text-center text-muted-foreground">لا توجد بيانات ورديات ضمن النطاق المحدد.</TableCell></TableRow> : posShiftsReport.summaryByUser.map((row) => (
                      <TableRow key={row.userId}>
                        <TableCell>{row.userName}</TableCell>
                        <TableCell className="text-right">{row.shiftsCount}</TableCell>
                        <TableCell className="text-right">{row.activeShiftsCount}</TableCell>
                        <TableCell className="text-right">{row.closedShiftsCount}</TableCell>
                        <TableCell className="text-right">{row.invoicesCount}</TableCell>
                        <TableCell className="text-right">{row.returnsCount}</TableCell>
                        <TableCell className="text-right">{fmt(row.totalSalesAmount)}</TableCell>
                        <TableCell className="text-right">{fmt(row.cashVariance)}</TableCell>
                        <TableCell className="text-right">{fmt(row.visaVariance)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>معرّف الوردية</TableHead>
                      <TableHead>المستخدم</TableHead>
                      <TableHead>الحالة</TableHead>
                      <TableHead>بداية</TableHead>
                      <TableHead>نهاية</TableHead>
                      <TableHead className="text-right">المبيعات</TableHead>
                      <TableHead className="text-right">فواتير</TableHead>
                      <TableHead className="text-right">مرتجع</TableHead>
                      <TableHead className="text-right">نقد</TableHead>
                      <TableHead className="text-right">بطاقة</TableHead>
                      <TableHead className="text-right">فرق النقد</TableHead>
                      <TableHead className="text-right">فرق البطاقة</TableHead>
                      <TableHead className="text-center">حالة الترحيل</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {transferredPosShiftSessions.length === 0 ? <TableRow><TableCell colSpan={13} className="py-8 text-center text-muted-foreground">لا توجد ورديات مرحلة إلى الصندوق الرئيسي.</TableCell></TableRow> : transferredPosShiftSessions.map((row) => (
                      <TableRow key={row.id}>
                        <TableCell>{row.id}</TableCell>
                        <TableCell>{row.userName}</TableCell>
                        <TableCell>{row.status === 'active' ? 'نشطة' : 'مغلقة'}</TableCell>
                        <TableCell>{row.startedAt || '-'}</TableCell>
                        <TableCell>{row.endedAt || '-'}</TableCell>
                        <TableCell className="text-right">{fmt(row.totalSalesAmount)}</TableCell>
                        <TableCell className="text-right">{row.invoicesCount}</TableCell>
                        <TableCell className="text-right">{row.returnsCount}</TableCell>
                        <TableCell className="text-right">{fmt(row.cashSalesAmount)}</TableCell>
                        <TableCell className="text-right">{fmt(row.visaSalesAmount)}</TableCell>
                        <TableCell className="text-right">{fmt(row.cashVariance)}</TableCell>
                        <TableCell className="text-right">{fmt(row.visaVariance)}</TableCell>
                        <TableCell className="text-center font-semibold text-emerald-700">مرحلة</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
