'use client';

import { useMemo, useState } from 'react';
import { format } from 'date-fns';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { CheckCircle2, Truck, PackageCheck, XCircle, Eye, RefreshCw, RotateCcw } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

type StoreFulfillment = {
  shipmentId?: string;
  shipmentNumber?: string;
  shipmentCreatedAt?: string;
  salesInvoiceId?: string;
  salesInvoiceNumber?: string;
  postedAt?: string;
  salesReturnId?: string;
  salesReturnNumber?: string;
  returnCondition?: 'good' | 'damaged';
  returnReason?: string;
};

type StoreOrder = {
  id: string;
  invoiceNumber: string;
  date: string;
  createdAt?: string;
  customerName?: string;
  notes?: string;
  grandTotal: number;
  storeStatus?: string;
  storeCustomerPhone?: string;
  storeCustomerAddress?: string;
  items?: any[];
  storeFulfillment?: StoreFulfillment;
};

type Shelf = {
  id: string;
  name: string;
  inactive?: boolean;
};

type Warehouse = {
  id: string;
  name: string;
  inactive?: boolean;
  shelves?: Shelf[];
};

type Props = {
  orders: StoreOrder[];
  warehouses: Warehouse[];
  stockLocations: Record<string, Array<{ warehouseId: string; shelfId: string; quantity: number }>>;
};

type AllocationRow = {
  warehouseId: string;
  shelfId: string;
  quantity: number;
};

const STATUS_OPTIONS = [
  { value: 'all', label: 'كل الطلبات' },
  { value: 'pending', label: 'قيد الانتظار' },
  { value: 'confirmed', label: 'تم التأكيد' },
  { value: 'shipped', label: 'قيد الشحن' },
  { value: 'delivered', label: 'تم التسليم' },
  { value: 'cancelled', label: 'ملغي' },
];

function getStatusBadge(status: string) {
  switch (status) {
    case 'pending':
      return <Badge variant="outline" className="border-orange-400 text-orange-600">قيد الانتظار</Badge>;
    case 'confirmed':
      return <Badge variant="outline" className="border-blue-400 text-blue-600">تم التأكيد</Badge>;
    case 'shipped':
      return <Badge variant="outline" className="border-purple-400 text-purple-600">قيد الشحن</Badge>;
    case 'delivered':
      return <Badge variant="default" className="bg-green-600">تم التسليم</Badge>;
    case 'cancelled':
      return <Badge variant="destructive">ملغي</Badge>;
    default:
      return <Badge variant="outline">{status || 'قيد الانتظار'}</Badge>;
  }
}

function parseCustomerFromNotes(notes: string): { name: string; address: string; phone: string; note: string } {
  const result = { name: '', address: '', phone: '', note: '' };
  if (!notes) return result;
  const parts = notes.split('|').map((p) => p.trim());
  for (const part of parts) {
    if (part.startsWith('اسم:')) result.name = part.replace('اسم:', '').trim();
    else if (part.startsWith('عنوان:')) result.address = part.replace('عنوان:', '').trim();
    else if (part.startsWith('جوال:')) result.phone = part.replace('جوال:', '').trim();
    else if (part.startsWith('ملاحظة:')) result.note = part.replace('ملاحظة:', '').trim();
  }
  return result;
}

function normalizeId(value: unknown) {
  return String(value ?? '').trim();
}

export default function StoreOrdersClient({ orders: initialOrders, warehouses, stockLocations }: Props) {
  const { toast } = useToast();
  const [orders, setOrders] = useState<StoreOrder[]>(initialOrders);
  const [statusFilter, setStatusFilter] = useState('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [fromDate, setFromDate] = useState('');
  const [toDate, setToDate] = useState('');
  const [detailOrder, setDetailOrder] = useState<StoreOrder | null>(null);
  const [confirmOrder, setConfirmOrder] = useState<StoreOrder | null>(null);
  const [lineAllocations, setLineAllocations] = useState<AllocationRow[][]>([]);
  const [updatingId, setUpdatingId] = useState<string | null>(null);
  const [returnOrder, setReturnOrder] = useState<StoreOrder | null>(null);
  const [returnCondition, setReturnCondition] = useState<'good' | 'damaged'>('good');
  const [returnReason, setReturnReason] = useState('');
  const [returnRefundMethod, setReturnRefundMethod] = useState<'credit_to_account' | 'cash' | 'bank_transfer' | 'check'>('credit_to_account');

  const activeWarehouses = useMemo(
    () => (warehouses || []).filter((warehouse) => !warehouse.inactive),
    [warehouses]
  );

  const warehouseById = useMemo(
    () => new Map(activeWarehouses.map((warehouse) => [normalizeId(warehouse.id), warehouse])),
    [activeWarehouses]
  );

  const stockLocationsByMaterial = useMemo(() => stockLocations || {}, [stockLocations]);

  const getAvailableForLocation = (materialId: string, warehouseId: string, shelfId: string) => {
    const locations = stockLocationsByMaterial[normalizeId(materialId)] || [];
    const normalizedWarehouseId = normalizeId(warehouseId);
    const normalizedShelfId = normalizeId(shelfId);
    const location = locations.find(
      (entry) => normalizeId(entry.warehouseId) === normalizedWarehouseId && normalizeId(entry.shelfId) === normalizedShelfId
    );
    return Number(location?.quantity || 0);
  };

  const getMaxQuantityForRow = (itemIndex: number, allocationIndex: number) => {
    const orderItems = Array.isArray(confirmOrder?.items) ? confirmOrder.items : [];
    const materialId = normalizeId(orderItems[itemIndex]?.materialId);
    const rows = Array.isArray(lineAllocations[itemIndex]) ? lineAllocations[itemIndex] : [];
    const row = rows[allocationIndex];
    if (!row) return 0;

    const warehouseId = normalizeId(row.warehouseId);
    const shelfId = normalizeId(row.shelfId);
    if (!warehouseId || !shelfId) return 0;

    const availableAtLocation = getAvailableForLocation(materialId, warehouseId, shelfId);
    const allocatedByOtherRows = rows.reduce((sum, entry, idx) => {
      if (idx === allocationIndex) return sum;
      if (normalizeId(entry.warehouseId) !== warehouseId) return sum;
      if (normalizeId(entry.shelfId) !== shelfId) return sum;
      return sum + Number(entry.quantity || 0);
    }, 0);

    return Math.max(0, availableAtLocation - allocatedByOtherRows);
  };

  const filteredOrders = useMemo(() => {
    const q = searchQuery.trim().toLowerCase();
    return orders.filter((order) => {
      const customer = parseCustomerFromNotes(order.notes || '');
      const status = order.storeStatus || 'pending';
      const dateStr = format(new Date(order.createdAt || order.date || Date.now()), 'yyyy-MM-dd');

      if (statusFilter !== 'all' && status !== statusFilter) return false;
      if (fromDate && dateStr < fromDate) return false;
      if (toDate && dateStr > toDate) return false;
      if (q) {
        const text = [
          order.invoiceNumber,
          customer.name,
          customer.phone,
          customer.address,
          order.notes,
        ].join(' ').toLowerCase();
        if (!text.includes(q)) return false;
      }
      return true;
    });
  }, [orders, statusFilter, searchQuery, fromDate, toDate]);

  const stats = useMemo(() => ({
    total: orders.length,
    pending: orders.filter((o) => !o.storeStatus || o.storeStatus === 'pending').length,
    confirmed: orders.filter((o) => o.storeStatus === 'confirmed').length,
    shipped: orders.filter((o) => o.storeStatus === 'shipped').length,
    delivered: orders.filter((o) => o.storeStatus === 'delivered').length,
    cancelled: orders.filter((o) => o.storeStatus === 'cancelled').length,
    totalRevenue: orders
      .filter((o) => o.storeStatus !== 'cancelled')
      .reduce((sum, o) => sum + Number(o.grandTotal || 0), 0),
  }), [orders]);

  const updateStatus = async (
    orderId: string,
    newStatus: string,
    options?: {
      lineLocations?: Array<{ index: number; warehouseId: string; shelfId: string }>;
      lineAllocations?: Array<{ index: number; allocations: Array<{ warehouseId: string; shelfId: string; quantity: number }> }>;
      returnHandling?: {
        condition: 'good' | 'damaged';
        reason: string;
        refundMethod: 'credit_to_account' | 'cash' | 'bank_transfer' | 'check';
      };
    }
  ) => {
    setUpdatingId(orderId);
    try {
      const response = await fetch(`/api/store/orders/${orderId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ storeStatus: newStatus, ...(options || {}) }),
      });
      const data = await response.json().catch(() => ({}));
      if (!response.ok) {
        toast({ title: 'خطأ', description: data?.error || 'فشل تحديث الحالة', variant: 'destructive' });
        return;
      }
      setOrders((prev) => prev.map((o) => (o.id === orderId ? (data.order || { ...o, storeStatus: newStatus, ...(data.storeFulfillment ? { storeFulfillment: data.storeFulfillment } : {}) }) : o)));
      if (detailOrder?.id === orderId && data.order) setDetailOrder(data.order);
      if (confirmOrder?.id === orderId && data.order) setConfirmOrder(data.order);
      toast({ title: 'تم التحديث', description: `تم تغيير حالة الطلب إلى: ${STATUS_OPTIONS.find((s) => s.value === newStatus)?.label || newStatus}` });
    } catch {
      toast({ title: 'خطأ', description: 'تعذر الاتصال بالخادم', variant: 'destructive' });
    } finally {
      setUpdatingId(null);
    }
  };

  const openConfirmDialog = (order: StoreOrder) => {
    const orderItems = Array.isArray(order.items) ? order.items : [];
    setLineAllocations(
      orderItems.map((item: any) => {
        const materialId = normalizeId(item?.materialId);
        const availableLocations = stockLocationsByMaterial[materialId] || [];
        const itemQty = Number(item?.quantity || 0);
        const warehouseId = normalizeId(item?.warehouseId);
        const shelfId = normalizeId(item?.shelfId);
        if (
          warehouseId &&
          shelfId &&
          availableLocations.some(
            (location) => normalizeId(location.warehouseId) === warehouseId && normalizeId(location.shelfId) === shelfId
          )
        ) {
          return [{ warehouseId, shelfId, quantity: itemQty }];
        }

        if (availableLocations.length === 1) {
          return [{
            warehouseId: availableLocations[0].warehouseId,
            shelfId: availableLocations[0].shelfId,
            quantity: itemQty,
          }];
        }

        if (activeWarehouses.length === 1) {
          const onlyWarehouse = activeWarehouses[0];
          const activeShelves = (onlyWarehouse.shelves || []).filter((shelf) => !shelf.inactive);
          if (activeShelves.length === 1) {
            return [{ warehouseId: onlyWarehouse.id, shelfId: activeShelves[0].id, quantity: itemQty }];
          }
          return [{ warehouseId: onlyWarehouse.id, shelfId: '', quantity: itemQty }];
        }

        return [{ warehouseId: '', shelfId: '', quantity: itemQty }];
      })
    );
    setConfirmOrder(order);
  };

  const setAllocationAt = (itemIndex: number, allocationIndex: number, patch: Partial<AllocationRow>) => {
    setLineAllocations((prev) =>
      prev.map((rows, rowIndex) =>
        rowIndex !== itemIndex
          ? rows
          : rows.map((row, idx) => (idx === allocationIndex ? { ...row, ...patch } : row))
      )
    );
  };

  const addAllocationRow = (itemIndex: number) => {
    setLineAllocations((prev) =>
      prev.map((rows, rowIndex) =>
        rowIndex !== itemIndex ? rows : [...rows, { warehouseId: '', shelfId: '', quantity: 0 }]
      )
    );
  };

  const removeAllocationRow = (itemIndex: number, allocationIndex: number) => {
    setLineAllocations((prev) =>
      prev.map((rows, rowIndex) => {
        if (rowIndex !== itemIndex) return rows;
        if (rows.length <= 1) return rows;
        return rows.filter((_, idx) => idx !== allocationIndex);
      })
    );
  };

  const submitConfirmOrder = async () => {
    if (!confirmOrder) return;
    const orderItems = Array.isArray(confirmOrder.items) ? confirmOrder.items : [];

    for (let index = 0; index < orderItems.length; index += 1) {
      const item = orderItems[index];
      const itemName = item?.materialName || item?.name || item?.materialId || `الصنف ${index + 1}`;
      const requestedQty = Number(item?.quantity || 0);
      const rows = Array.isArray(lineAllocations[index]) ? lineAllocations[index] : [];

      if (rows.length === 0) {
        toast({ title: 'خطأ', description: `يرجى تحديد رفوف الصنف: ${itemName}`, variant: 'destructive' });
        return;
      }

      const hasMissing = rows.some(
        (row) =>
          !String(row?.warehouseId || '').trim() ||
          !String(row?.shelfId || '').trim() ||
          !Number.isFinite(Number(row?.quantity || 0)) ||
          Number(row?.quantity || 0) <= 0
      );
      if (hasMissing) {
        toast({ title: 'خطأ', description: `أكمل المستودع/الرف/الكمية لكل توزيع في الصنف: ${itemName}`, variant: 'destructive' });
        return;
      }

      const totalAllocated = rows.reduce((sum, row) => sum + Number(row.quantity || 0), 0);
      if (Math.abs(totalAllocated - requestedQty) > 0.0001) {
        toast({
          title: 'خطأ',
          description: `مجموع التوزيع للصنف ${itemName} يجب أن يساوي ${requestedQty} (الحالي: ${totalAllocated})`,
          variant: 'destructive',
        });
        return;
      }

      const locationSums = new Map<string, number>();
      for (const row of rows) {
        const key = `${String(row.warehouseId || '').trim()}||${String(row.shelfId || '').trim()}`;
        locationSums.set(key, (locationSums.get(key) || 0) + Number(row.quantity || 0));
      }

      for (const [locationKey, allocatedQty] of locationSums.entries()) {
        const [warehouseId, shelfId] = locationKey.split('||');
        const availableQty = getAvailableForLocation(String(item?.materialId || ''), warehouseId, shelfId);
        if (allocatedQty - availableQty > 0.0001) {
          toast({
            title: 'خطأ',
            description: `الكمية الموزعة للصنف ${itemName} على الرف المحدد (${allocatedQty}) تتجاوز المتاح (${availableQty})`,
            variant: 'destructive',
          });
          return;
        }
      }
    }

    await updateStatus(confirmOrder.id, 'confirmed', {
      lineLocations: lineAllocations.map((rows, index) => ({
        index,
        warehouseId: rows[0]?.warehouseId || '',
        shelfId: rows[0]?.shelfId || '',
      })),
      lineAllocations: lineAllocations.map((rows, index) => ({
        index,
        allocations: rows.map((row) => ({
          warehouseId: row.warehouseId,
          shelfId: row.shelfId,
          quantity: Number(row.quantity || 0),
        })),
      })),
    });
    setConfirmOrder(null);
  };

  const submitDeliveredReturn = async () => {
    if (!returnOrder) return;
    const reason = returnReason.trim();
    if (!reason) {
      toast({ title: 'خطأ', description: 'يرجى إدخال سبب المردود', variant: 'destructive' });
      return;
    }
    await updateStatus(returnOrder.id, 'cancelled', {
      returnHandling: {
        condition: returnCondition,
        reason,
        refundMethod: returnRefundMethod,
      },
    });
    setReturnOrder(null);
    setReturnReason('');
    setReturnCondition('good');
    setReturnRefundMethod('credit_to_account');
  };

  const formatCurrency = (amount: number) =>
    Number(amount || 0).toLocaleString('ar-SA', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  return (
    <TooltipProvider>
      {/* Stats */}
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
        {[
          { label: 'إجمالي الطلبات', value: stats.total, color: 'text-foreground' },
          { label: 'قيد الانتظار', value: stats.pending, color: 'text-orange-600' },
          { label: 'مؤكدة', value: stats.confirmed, color: 'text-blue-600' },
          { label: 'قيد الشحن', value: stats.shipped, color: 'text-purple-600' },
          { label: 'مُسلّمة', value: stats.delivered, color: 'text-green-600' },
          { label: 'ملغية', value: stats.cancelled, color: 'text-destructive' },
        ].map((stat) => (
          <div key={stat.label} className="rounded-lg border bg-background p-3 text-center">
            <p className={`text-2xl font-bold ${stat.color}`}>{stat.value}</p>
            <p className="text-xs text-muted-foreground mt-1">{stat.label}</p>
          </div>
        ))}
      </div>

      {/* Filters */}
      <div className="flex flex-wrap gap-2 rounded-lg border bg-muted/20 p-3">
        <Input
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          placeholder="بحث بالاسم أو الجوال أو رقم الطلب..."
          className="w-64"
        />
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="h-10 rounded-md border bg-background px-3 text-sm"
        >
          {STATUS_OPTIONS.map((s) => (
            <option key={s.value} value={s.value}>{s.label}</option>
          ))}
        </select>
        <Input type="date" value={fromDate} onChange={(e) => setFromDate(e.target.value)} className="w-40" />
        <Input type="date" value={toDate} onChange={(e) => setToDate(e.target.value)} className="w-40" />
        <Button
          variant="outline"
          size="sm"
          onClick={() => { setSearchQuery(''); setStatusFilter('all'); setFromDate(''); setToDate(''); }}
        >
          إعادة ضبط
        </Button>
      </div>

      {/* Table */}
      <div className="rounded-lg border overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>رقم الطلب</TableHead>
              <TableHead>التاريخ</TableHead>
              <TableHead>العميل</TableHead>
              <TableHead>الجوال</TableHead>
              <TableHead>العنوان</TableHead>
              <TableHead className="text-right">المبلغ</TableHead>
              <TableHead>الحالة</TableHead>
              <TableHead>الفاتورة/المردود</TableHead>
              <TableHead>إجراءات</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredOrders.length === 0 ? (
              <TableRow>
                  <TableCell colSpan={9} className="py-10 text-center text-muted-foreground">
                  لا توجد طلبات مطابقة للفلتر المحدد
                </TableCell>
              </TableRow>
            ) : (
              filteredOrders.map((order) => {
                const customer = parseCustomerFromNotes(order.notes || '');
                const status = order.storeStatus || 'pending';
                const isUpdating = updatingId === order.id;
                const dateStr = format(
                  new Date(order.createdAt || order.date || Date.now()),
                  'yyyy-MM-dd HH:mm'
                );

                return (
                  <TableRow key={order.id}>
                    <TableCell className="font-mono text-xs">{order.invoiceNumber}</TableCell>
                    <TableCell className="text-xs text-muted-foreground whitespace-nowrap">{dateStr}</TableCell>
                    <TableCell>{customer.name || order.customerName || '—'}</TableCell>
                    <TableCell dir="ltr" className="font-mono text-sm">{customer.phone || '—'}</TableCell>
                    <TableCell className="max-w-[150px] truncate text-sm text-muted-foreground">
                      {customer.address || '—'}
                    </TableCell>
                    <TableCell className="text-right font-bold">{formatCurrency(order.grandTotal)}</TableCell>
                    <TableCell>{getStatusBadge(status)}</TableCell>
                    <TableCell>
                      {order.storeFulfillment?.salesReturnNumber ? (
                        <Badge variant="outline" className="border-amber-500 text-amber-700 text-xs whitespace-nowrap">
                          مردود: {order.storeFulfillment.salesReturnNumber}
                        </Badge>
                      ) : order.storeFulfillment?.salesInvoiceNumber ? (
                        <Badge variant="outline" className="border-green-500 text-green-700 text-xs whitespace-nowrap">
                          فاتورة: {order.storeFulfillment.salesInvoiceNumber}
                        </Badge>
                      ) : order.storeFulfillment?.shipmentNumber ? (
                        <Badge variant="outline" className="border-blue-500 text-blue-700 text-xs whitespace-nowrap">
                          إرسالية: {order.storeFulfillment.shipmentNumber}
                        </Badge>
                      ) : null}
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1">
                        {/* View detail */}
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => setDetailOrder(order)}>
                              <Eye className="h-4 w-4" />
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent>تفاصيل الطلب</TooltipContent>
                        </Tooltip>

                        {/* Confirm */}
                        {status === 'pending' && (
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button size="icon" variant="ghost" className="h-7 w-7 text-blue-600" onClick={() => openConfirmDialog(order)} disabled={isUpdating}>
                                <CheckCircle2 className="h-4 w-4" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>اعتماد الطلب وإصدار إرسالية</TooltipContent>
                          </Tooltip>
                        )}

                        {/* Ship */}
                        {status === 'confirmed' && (
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button size="icon" variant="ghost" className="h-7 w-7 text-purple-600" onClick={() => updateStatus(order.id, 'shipped')} disabled={isUpdating}>
                                <Truck className="h-4 w-4" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>ترحيل الإرسالية إلى فاتورة ضريبية</TooltipContent>
                          </Tooltip>
                        )}

                        {/* Deliver */}
                        {status === 'shipped' && (
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button size="icon" variant="ghost" className="h-7 w-7 text-green-600" onClick={() => updateStatus(order.id, 'delivered')} disabled={isUpdating}>
                                <PackageCheck className="h-4 w-4" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>تأكيد التسليم</TooltipContent>
                          </Tooltip>
                        )}

                        {/* Cancel */}
                        {['pending', 'confirmed'].includes(status) && (
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button size="icon" variant="ghost" className="h-7 w-7 text-destructive" onClick={() => updateStatus(order.id, 'cancelled')} disabled={isUpdating}>
                                <XCircle className="h-4 w-4" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>إلغاء الطلب</TooltipContent>
                          </Tooltip>
                        )}

                        {/* Return delivered order */}
                        {status === 'delivered' && (
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button
                                size="icon"
                                variant="ghost"
                                className="h-7 w-7 text-amber-600"
                                onClick={() => {
                                  setReturnOrder(order);
                                  setReturnCondition('good');
                                  setReturnReason('');
                                  setReturnRefundMethod('credit_to_account');
                                }}
                                disabled={isUpdating}
                              >
                                <RotateCcw className="h-4 w-4" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>تسجيل مردود</TooltipContent>
                          </Tooltip>
                        )}

                        {/* Re-open delivered/cancelled */}
                        {['delivered', 'cancelled'].includes(status) && (
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground" onClick={() => updateStatus(order.id, 'pending')} disabled={isUpdating}>
                                <RefreshCw className="h-4 w-4" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>إعادة فتح</TooltipContent>
                          </Tooltip>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </div>

      <Dialog open={!!confirmOrder} onOpenChange={(open) => { if (!open) setConfirmOrder(null); }}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>اعتماد طلب المتجر وإصدار إرسالية</DialogTitle>
            <DialogDescription>
              {confirmOrder ? `حدّد المستودع والرف لكل صنف في الطلب ${confirmOrder.invoiceNumber} قبل الاعتماد.` : ''}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3 max-h-[60vh] overflow-y-auto">
            {(Array.isArray(confirmOrder?.items) ? confirmOrder?.items : []).map((item: any, index: number) => {
              const materialId = normalizeId(item?.materialId);
              const materialLocations = stockLocationsByMaterial[materialId] || [];
              const rows = Array.isArray(lineAllocations[index]) ? lineAllocations[index] : [];
              const allowedWarehouseIds = new Set(materialLocations.map((location) => normalizeId(location.warehouseId)));
              const availableWarehouses = allowedWarehouseIds.size > 0
                ? activeWarehouses.filter((warehouse) => allowedWarehouseIds.has(normalizeId(warehouse.id)))
                : activeWarehouses;
              const requestedQty = Number(item?.quantity || 0);
              const allocatedQty = rows.reduce((sum, row) => sum + Number(row?.quantity || 0), 0);
              const hasLocationData = materialLocations.length > 0;
              const locationSummary = materialLocations
                .slice(0, 4)
                .map((location) => {
                  const warehouseName = warehouseById.get(normalizeId(location.warehouseId))?.name || normalizeId(location.warehouseId);
                  const shelfName = (warehouseById.get(normalizeId(location.warehouseId))?.shelves || []).find(
                    (shelf) => normalizeId(shelf.id) === normalizeId(location.shelfId)
                  )?.name || normalizeId(location.shelfId);
                  return `${warehouseName} / ${shelfName}: ${Number(location.quantity || 0)}`;
                })
                .join(' - ');
              return (
                <div key={`${confirmOrder?.id || 'order'}-${index}`} className="space-y-3 rounded-md border p-3">
                  <div>
                    <p className="text-sm font-medium">{item.materialName || item.name || item.materialId}</p>
                    <p className="text-xs text-muted-foreground">الكمية المطلوبة: {requestedQty} | الموزع: {allocatedQty}</p>
                    <p className="text-xs text-muted-foreground mt-1">المواقع المكتشفة لهذا الصنف: {materialLocations.length}</p>
                    {hasLocationData && (
                      <p className="text-xs text-muted-foreground mt-1">{locationSummary}{materialLocations.length > 4 ? ' ...' : ''}</p>
                    )}
                    {!hasLocationData && (
                      <p className="text-xs text-amber-600 mt-1">لا توجد مواقع مخزون مسجلة لهذا الصنف حالياً، اختر المستودع والرف يدوياً.</p>
                    )}
                  </div>
                  <div className="space-y-2">
                    {rows.map((row, allocIdx) => {
                      const selectedWarehouseId = normalizeId(row?.warehouseId);
                      const selectedShelfId = normalizeId(row?.shelfId);
                      const allowedShelfIds = new Set(
                        materialLocations
                          .filter((location) => normalizeId(location.warehouseId) === selectedWarehouseId)
                          .map((location) => normalizeId(location.shelfId))
                      );
                      const availableShelves = (warehouseById.get(selectedWarehouseId)?.shelves || []).filter(
                        (shelf) => !shelf.inactive && (allowedShelfIds.size === 0 || allowedShelfIds.has(normalizeId(shelf.id)))
                      );
                      const maxQtyForRow = getMaxQuantityForRow(index, allocIdx);
                      const locationAvailable = selectedWarehouseId && selectedShelfId
                        ? getAvailableForLocation(materialId, selectedWarehouseId, selectedShelfId)
                        : 0;

                      return (
                        <div key={`${index}-${allocIdx}`} className="grid gap-2 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_120px_48px] items-end">
                          <div className="space-y-1">
                            <Label>المستودع</Label>
                            <select
                              value={row.warehouseId}
                              onChange={(e) => setAllocationAt(index, allocIdx, { warehouseId: e.target.value, shelfId: '' })}
                              className="h-10 w-full rounded-md border bg-background px-3 text-sm"
                            >
                              <option value="">اختر المستودع</option>
                              {availableWarehouses.map((warehouse) => (
                                <option key={warehouse.id} value={warehouse.id}>{warehouse.name}</option>
                              ))}
                            </select>
                          </div>
                          <div className="space-y-1">
                            <Label>الرف</Label>
                            <select
                              value={row.shelfId}
                              onChange={(e) => setAllocationAt(index, allocIdx, { shelfId: e.target.value })}
                              className="h-10 w-full rounded-md border bg-background px-3 text-sm"
                              disabled={!selectedWarehouseId}
                            >
                              <option value="">اختر الرف</option>
                              {availableShelves.map((shelf) => (
                                <option key={shelf.id} value={shelf.id}>{shelf.name}</option>
                              ))}
                            </select>
                          </div>
                          <div className="space-y-1">
                            <Label>الكمية</Label>
                            <Input
                              type="number"
                              min={0}
                              step="0.01"
                              max={maxQtyForRow || undefined}
                              value={Number.isFinite(Number(row.quantity)) ? row.quantity : 0}
                              onChange={(e) => {
                                const raw = Number(e.target.value || 0);
                                const next = Math.min(Math.max(0, raw), maxQtyForRow || 0);
                                setAllocationAt(index, allocIdx, { quantity: next });
                              }}
                            />
                            {selectedWarehouseId && selectedShelfId && (
                              <p className="text-[11px] text-muted-foreground">المتاح على الرف: {locationAvailable}</p>
                            )}
                          </div>
                          <Button
                            type="button"
                            variant="outline"
                            size="icon"
                            onClick={() => removeAllocationRow(index, allocIdx)}
                            disabled={rows.length <= 1}
                          >
                            ×
                          </Button>
                        </div>
                      );
                    })}
                    <Button type="button" variant="secondary" size="sm" onClick={() => addAllocationRow(index)}>
                      إضافة رف آخر
                    </Button>
                  </div>
                </div>
              );
            })}
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setConfirmOrder(null)}>إلغاء</Button>
            <Button type="button" onClick={submitConfirmOrder} disabled={updatingId === confirmOrder?.id}>اعتماد وإصدار الإرسالية</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={!!returnOrder} onOpenChange={(open) => { if (!open) setReturnOrder(null); }}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>تسجيل مردود طلب متجر</DialogTitle>
            <DialogDescription>
              {returnOrder ? `الطلب: ${returnOrder.invoiceNumber} — سيتم إنشاء مردود مبيعات وربطه بالطلب` : ''}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>حالة الأصناف المرتجعة</Label>
              <select
                value={returnCondition}
                onChange={(e) => setReturnCondition((e.target.value as 'good' | 'damaged') || 'good')}
                className="h-10 w-full rounded-md border bg-background px-3 text-sm"
              >
                <option value="good">سليم (يرجع للمخزون)</option>
                <option value="damaged">تالف (لا يرجع للمخزون)</option>
              </select>
            </div>
            <div className="space-y-2">
              <Label>طريقة رد المبلغ</Label>
              <select
                value={returnRefundMethod}
                onChange={(e) => setReturnRefundMethod((e.target.value as 'credit_to_account' | 'cash' | 'bank_transfer' | 'check') || 'credit_to_account')}
                className="h-10 w-full rounded-md border bg-background px-3 text-sm"
              >
                <option value="credit_to_account">إضافة كرصيد للعميل</option>
                <option value="cash">نقداً</option>
                <option value="bank_transfer">تحويل بنكي</option>
                <option value="check">شيك</option>
              </select>
            </div>
            <div className="space-y-2">
              <Label>سبب المردود</Label>
              <Textarea
                value={returnReason}
                onChange={(e) => setReturnReason(e.target.value)}
                placeholder="مثال: العميل رفض الطلب عند الاستلام"
                rows={3}
              />
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setReturnOrder(null)}>إلغاء</Button>
            <Button type="button" variant="destructive" onClick={submitDeliveredReturn} disabled={updatingId === returnOrder?.id}>تأكيد المردود</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Detail Dialog */}
      <Dialog open={!!detailOrder} onOpenChange={(open) => { if (!open) setDetailOrder(null); }}>
        {detailOrder && (() => {
          const customer = parseCustomerFromNotes(detailOrder.notes || '');
          const items = Array.isArray(detailOrder.items) ? detailOrder.items : [];
          return (
            <DialogContent className="max-w-lg">
              <DialogHeader>
                <DialogTitle>تفاصيل الطلب — {detailOrder.invoiceNumber}</DialogTitle>
                <DialogDescription>
                  {format(new Date(detailOrder.createdAt || detailOrder.date || Date.now()), 'yyyy-MM-dd HH:mm')}
                </DialogDescription>
              </DialogHeader>
              <div className="space-y-4">
                <div className="rounded-md border p-3 space-y-1 text-sm">
                  <p><span className="font-medium">الاسم:</span> {customer.name || '—'}</p>
                  <p><span className="font-medium">الجوال:</span> <span dir="ltr">{customer.phone || '—'}</span></p>
                  <p><span className="font-medium">العنوان:</span> {customer.address || '—'}</p>
                  {customer.note && <p><span className="font-medium">ملاحظة:</span> {customer.note}</p>}
                </div>
                <div className="space-y-2">
                  <p className="text-sm font-medium">المنتجات:</p>
                  {items.length === 0 ? (
                    <p className="text-sm text-muted-foreground">لا تفاصيل للمنتجات</p>
                  ) : (
                    <div className="rounded-md border divide-y text-sm">
                      {items.map((item: any, idx: number) => (
                        <div key={idx} className="flex justify-between gap-3 px-3 py-2">
                          <div>
                            <span>{item.materialName || item.name || item.materialId} × {item.quantity}</span>
                            {(item.warehouseId || item.shelfId) && (
                              <p className="text-xs text-muted-foreground mt-1">
                                {warehouseById.get(String(item.warehouseId || '').trim())?.name || item.warehouseId || '—'}
                                {' / '}
                                {((warehouseById.get(String(item.warehouseId || '').trim())?.shelves || []).find((shelf) => shelf.id === String(item.shelfId || '').trim())?.name) || item.shelfId || '—'}
                              </p>
                            )}
                          </div>
                          <span>{formatCurrency(Number(item.total || item.unitPrice * item.quantity || 0))}</span>
                        </div>
                      ))}
                      <div className="flex justify-between px-3 py-2 font-bold">
                        <span>الإجمالي</span>
                        <span>{formatCurrency(detailOrder.grandTotal)}</span>
                      </div>
                    </div>
                  )}
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-sm font-medium">الحالة:</span>
                  {getStatusBadge(detailOrder.storeStatus || 'pending')}
                </div>
                {detailOrder.storeFulfillment && (
                  <div className="rounded-md border p-3 space-y-1 text-sm bg-muted/30">
                    <p className="font-medium mb-1">معلومات التسوية</p>
                    {detailOrder.storeFulfillment.shipmentNumber && (
                      <p><span className="text-muted-foreground">الإرسالية:</span> <span className="font-mono">{detailOrder.storeFulfillment.shipmentNumber}</span></p>
                    )}
                    {detailOrder.storeFulfillment.shipmentCreatedAt && (
                      <p><span className="text-muted-foreground">تاريخ الإرسالية:</span> {format(new Date(detailOrder.storeFulfillment.shipmentCreatedAt), 'yyyy-MM-dd')}</p>
                    )}
                    {detailOrder.storeFulfillment.salesInvoiceNumber && (
                      <p><span className="text-muted-foreground">فاتورة المبيعات:</span> <span className="font-mono">{detailOrder.storeFulfillment.salesInvoiceNumber}</span></p>
                    )}
                    {detailOrder.storeFulfillment.postedAt && (
                      <p><span className="text-muted-foreground">تاريخ الترحيل:</span> {format(new Date(detailOrder.storeFulfillment.postedAt), 'yyyy-MM-dd')}</p>
                    )}
                    {detailOrder.storeFulfillment.salesReturnNumber && (
                      <p><span className="text-muted-foreground">رقم المردود:</span> <span className="font-mono">{detailOrder.storeFulfillment.salesReturnNumber}</span></p>
                    )}
                    {detailOrder.storeFulfillment.returnCondition && (
                      <p><span className="text-muted-foreground">حالة المرتجع:</span> {detailOrder.storeFulfillment.returnCondition === 'good' ? 'سليم' : 'تالف'}</p>
                    )}
                    {detailOrder.storeFulfillment.returnReason && (
                      <p><span className="text-muted-foreground">سبب المردود:</span> {detailOrder.storeFulfillment.returnReason}</p>
                    )}
                  </div>
                )}
              </div>
              <DialogFooter>
                <Button variant="outline" onClick={() => setDetailOrder(null)}>إغلاق</Button>
              </DialogFooter>
            </DialogContent>
          );
        })()}
      </Dialog>
    </TooltipProvider>
  );
}
