'use client';

import { useState, useTransition, useMemo } from 'react';
import { formatDateStable } from '@/lib/formatters';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { PlusCircle, Upload, Download, Trash2, Search, FileText } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { handleBulkUpsertItemUnits, handleUpdateItemUnitsStatus } from '@/lib/actions';
import type { ProductionItem, ItemUnit, Warehouse } from '@/lib/types';

type ItemUnitsManagerProps = {
  materials: ProductionItem[];
  itemUnits: ItemUnit[];
  warehouses: Warehouse[];
  t: any;
  tGlobal: any;
};

export default function ItemUnitsManager({ materials, itemUnits, warehouses, t, tGlobal }: ItemUnitsManagerProps) {
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();
  const [searchQuery, setSearchQuery] = useState('');
  const [filterMaterialId, setFilterMaterialId] = useState<string>('_all');
  const [filterStatus, setFilterStatus] = useState<string>('_all');
  const [filterWarehouseId, setFilterWarehouseId] = useState<string>('_all');
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showBulkDialog, setShowBulkDialog] = useState(false);
  const [showImportDialog, setShowImportDialog] = useState(false);
  const [selectedMaterialId, setSelectedMaterialId] = useState('');
  const [materialSearch, setMaterialSearch] = useState('');
  const [showMaterialSuggestions, setShowMaterialSuggestions] = useState(false);
  const [selectedWarehouseId, setSelectedWarehouseId] = useState('_none');
  const [bulkInput, setBulkInput] = useState('');
  const [csvInput, setCsvInput] = useState('');
  const [selectedUnits, setSelectedUnits] = useState<Set<string>>(new Set());

  const normalizeSearchText = (value: string) => {
    return value
      .toLowerCase()
      .replace(/[\u064B-\u065F\u0670\u06D6-\u06ED]/g, '')
      .replace(/[إأآٱ]/g, 'ا')
      .replace(/ى/g, 'ي')
      .replace(/ؤ/g, 'و')
      .replace(/ئ/g, 'ي')
      .replace(/ة/g, 'ه')
      .replace(/\s+/g, '')
      .replace(/[^\p{L}\p{N}]+/gu, '');
  };

  const sortCharsForAdvancedMatch = (value: string) => normalizeSearchText(value).split('').sort().join('');

  const matchesAdvancedTextSearch = (fields: Array<string | number | undefined | null>, rawQuery: string) => {
    const query = String(rawQuery || '').trim();
    if (!query) return true;

    const tokens = query
      .split(/\s+/)
      .map((part) => ({
        normalized: normalizeSearchText(part),
        sorted: sortCharsForAdvancedMatch(part),
      }))
      .filter((part) => part.normalized.length > 0);

    if (tokens.length === 0) return true;

    const normalizedFields = fields.map((field) => normalizeSearchText(String(field || ''))).filter(Boolean);
    const sortedFields = normalizedFields.map((field) => field.split('').sort().join(''));

    return tokens.every((token) =>
      normalizedFields.some((field) => field.includes(token.normalized))
      || sortedFields.some((field) => token.sorted && field.includes(token.sorted))
    );
  };

  const matchesAdvancedMaterialSearch = (candidate: ProductionItem, rawQuery: string) => {
    const query = String(rawQuery || '').trim();
    if (!query) return true;

    const tokens = query
      .split(/\s+/)
      .map((part) => ({
        normalized: normalizeSearchText(part),
        sorted: sortCharsForAdvancedMatch(part),
      }))
      .filter((part) => part.normalized.length > 0);

    if (tokens.length === 0) return true;

    const fields = [
      candidate.itemNumber,
      candidate.id,
      candidate.name,
      candidate.itemSymbolName || '',
      (candidate as any).globalReferenceNumber || '',
      candidate.barcode || '',
      candidate.secondaryBarcode || '',
      (candidate.additionalBarcodes || []).join(' '),
      candidate.additionalDetails || '',
      String(candidate.salePrice ?? ''),
      String(candidate.purchasePrice ?? ''),
    ];

    const normalizedFields = fields.map((field) => normalizeSearchText(String(field || ''))).filter(Boolean);
    const sortedFields = normalizedFields.map((field) => field.split('').sort().join(''));

    return tokens.every((token) =>
      normalizedFields.some((field) => field.includes(token.normalized))
      || sortedFields.some((field) => token.sorted && field.includes(token.sorted))
    );
  };

  const trackedMaterials = useMemo(() => 
    materials.filter(m => m.hasSerialNumber === true || m.hasRfid === true),
    [materials]
  );

  // Fallback to all materials if tracking flags are not configured yet.
  const selectableMaterials = useMemo(() => {
    return trackedMaterials.length > 0 ? trackedMaterials : materials;
  }, [trackedMaterials, materials]);

  const filteredTrackedMaterials = useMemo(() => {
    if (!materialSearch.trim()) return selectableMaterials;
    return selectableMaterials.filter((material) => matchesAdvancedMaterialSearch(material, materialSearch));
  }, [selectableMaterials, materialSearch]);

  const selectedMaterial = useMemo(() => 
    selectableMaterials.find(m => m.id === selectedMaterialId),
    [selectableMaterials, selectedMaterialId]
  );

  const filteredUnits = useMemo(() => {
    let result = [...itemUnits];

    if (filterMaterialId && filterMaterialId !== '_all') {
      result = result.filter(u => u.itemId === filterMaterialId);
    }

    if (filterStatus && filterStatus !== '_all') {
      result = result.filter(u => u.status === filterStatus);
    }

    if (filterWarehouseId && filterWarehouseId !== '_all') {
      result = result.filter(u => u.warehouseId === filterWarehouseId);
    }

    if (searchQuery.trim()) {
      result = result.filter((unit) => {
        const material = materials.find((m) => m.id === unit.itemId);
        const warehouse = warehouses.find((w) => w.id === unit.warehouseId);
        return matchesAdvancedTextSearch(
          [
            unit.serialNumber,
            unit.rfidCode,
            unit.notes,
            unit.location,
            unit.status,
            material?.name,
            material?.itemNumber,
            material?.barcode,
            warehouse?.name,
          ],
          searchQuery
        );
      });
    }

    return result.sort((a, b) => {
      const dateA = new Date(a.createdAt || 0).getTime();
      const dateB = new Date(b.createdAt || 0).getTime();
      return dateB - dateA;
    });
  }, [itemUnits, materials, warehouses, searchQuery, filterMaterialId, filterStatus, filterWarehouseId]);

  const handleBulkAdd = () => {
    if (!selectedMaterialId) {
      toast({
        title: tGlobal?.error ?? 'خطأ',
        description: t?.selectMaterialFirst ?? 'الرجاء اختيار الصنف أولاً',
        variant: 'destructive',
      });
      return;
    }

    const lines = bulkInput
      .split('\n')
      .map(line => line.trim())
      .filter(Boolean);

    if (lines.length === 0) {
      toast({
        title: tGlobal?.error ?? 'خطأ',
        description: t?.noDataEntered ?? 'لم يتم إدخال أي بيانات',
        variant: 'destructive',
      });
      return;
    }

    const material = materials.find(m => m.id === selectedMaterialId);
    const rows = lines.map(line => {
      const parts = line.split(/[,;\t]/).map(p => p.trim());
      if (material?.hasSerialNumber && material?.hasRfid && parts.length >= 2) {
        return { serialNumber: parts[0], rfidCode: parts[1] };
      } else if (material?.hasSerialNumber) {
        return { serialNumber: parts[0], rfidCode: '' };
      } else if (material?.hasRfid) {
        return { serialNumber: '', rfidCode: parts[0] };
      }
      return { serialNumber: parts[0] || '', rfidCode: parts[1] || '' };
    });

    startTransition(async () => {
      const result = await handleBulkUpsertItemUnits({
        itemId: selectedMaterialId,
        warehouseId: selectedWarehouseId === '_none' ? '' : selectedWarehouseId,
        rows,
      });

      if ('success' in result && result.success === true) {
        const successResult = result as { success: true; added: number; rejected: Array<{ row: number; reason: string }> };
        toast({
          title: t?.bulkAddSuccess ?? 'تمت الإضافة بنجاح',
          description: `${t?.added ?? 'تمت إضافة'}: ${successResult.added || 0}, ${t?.rejected ?? 'مرفوض'}: ${successResult.rejected?.length || 0}`,
        });
        setBulkInput('');
        setShowBulkDialog(false);
        setSelectedMaterialId('');
        setMaterialSearch('');
        setShowMaterialSuggestions(false);
        setSelectedWarehouseId('_none');
        window.location.reload();
      } else {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: ('error' in result ? result.error : t?.bulkAddFailed) ?? 'فشلت الإضافة الجماعية',
          variant: 'destructive',
        });
      }
    });
  };

  const handleImportCSV = () => {
    if (!selectedMaterialId) {
      toast({
        title: tGlobal?.error ?? 'خطأ',
        description: t?.selectMaterialFirst ?? 'الرجاء اختيار الصنف أولاً',
        variant: 'destructive',
      });
      return;
    }

    const lines = csvInput
      .split('\n')
      .map(line => line.trim())
      .filter(line => line && !line.toLowerCase().startsWith('serial') && !line.toLowerCase().startsWith('رقم'));

    if (lines.length === 0) {
      toast({
        title: tGlobal?.error ?? 'خطأ',
        description: t?.noDataEntered ?? 'لم يتم إدخال أي بيانات',
        variant: 'destructive',
      });
      return;
    }

    const rows = lines.map(line => {
      const parts = line.split(',').map(p => p.trim().replace(/^["']|["']$/g, ''));
      return {
        serialNumber: parts[0] || '',
        rfidCode: parts[1] || '',
      };
    });

    startTransition(async () => {
      const result = await handleBulkUpsertItemUnits({
        itemId: selectedMaterialId,
        warehouseId: selectedWarehouseId === '_none' ? '' : selectedWarehouseId,
        rows,
      });

      if ('success' in result && result.success === true) {
        const successResult = result as { success: true; added: number; rejected: Array<{ row: number; reason: string }> };
        toast({
          title: t?.importSuccess ?? 'تم الاستيراد بنجاح',
          description: `${t?.added ?? 'تمت إضافة'}: ${successResult.added || 0}, ${t?.rejected ?? 'مرفوض'}: ${successResult.rejected?.length || 0}`,
        });
        setCsvInput('');
        setShowImportDialog(false);
        setSelectedMaterialId('');
        setMaterialSearch('');
        setShowMaterialSuggestions(false);
        setSelectedWarehouseId('_none');
        window.location.reload();
      } else {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: ('error' in result ? result.error : t?.importFailed) ?? 'فشل الاستيراد',
          variant: 'destructive',
        });
      }
    });
  };

  const handleBulkStatusChange = (newStatus: ItemUnit['status']) => {
    if (selectedUnits.size === 0) {
      toast({
        title: tGlobal?.error ?? 'خطأ',
        description: t?.noUnitsSelected ?? 'لم يتم اختيار أي وحدات',
        variant: 'destructive',
      });
      return;
    }

    startTransition(async () => {
      const result = await handleUpdateItemUnitsStatus({
        unitIds: Array.from(selectedUnits),
        status: newStatus,
      });

      if ('success' in result && result.success === true) {
        const successResult = result as { success: true; changed: number };
        toast({
          title: t?.statusUpdateSuccess ?? 'تم تحديث الحالة',
          description: `${t?.updated ?? 'تم التحديث'}: ${successResult.changed || 0}`,
        });
        setSelectedUnits(new Set());
        window.location.reload();
      } else {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: ('error' in result ? result.error : t?.statusUpdateFailed) ?? 'فشل تحديث الحالة',
          variant: 'destructive',
        });
      }
    });
  };

  const toggleUnitSelection = (unitId: string) => {
    setSelectedUnits(prev => {
      const next = new Set(prev);
      if (next.has(unitId)) {
        next.delete(unitId);
      } else {
        next.add(unitId);
      }
      return next;
    });
  };

  const toggleAllSelection = () => {
    if (selectedUnits.size === filteredUnits.length) {
      setSelectedUnits(new Set());
    } else {
      setSelectedUnits(new Set(filteredUnits.map(u => u.id)));
    }
  };

  const exportToCSV = () => {
    const headers = [
      t?.serialNumberLabel ?? 'الرقم التسلسلي',
      t?.rfidCodeLabel ?? 'RFID',
      t?.materialLabel ?? 'الصنف',
      t?.status ?? 'الحالة',
      t?.warehouseLabel ?? 'المستودع',
      t?.location ?? 'الموقع',
      t?.notesLabel ?? 'ملاحظات',
    ];

    const rows = filteredUnits.map(unit => {
      const material = materials.find(m => m.id === unit.itemId);
      const warehouse = warehouses.find(w => w.id === unit.warehouseId);
      return [
        unit.serialNumber || '-',
        unit.rfidCode || '-',
        material?.name || '-',
        unit.status,
        warehouse?.name || '-',
        unit.location || '-',
        unit.notes || '-',
      ];
    });

    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.map(cell => `"${cell}"`).join(',')),
    ].join('\n');

    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `item-units-${new Date().toISOString().slice(0, 10)}.csv`;
    link.click();
  };

  const getStatusBadgeVariant = (status: ItemUnit['status']) => {
    switch (status) {
      case 'available':
      case 'in_stock':
        return 'default';
      case 'sold':
        return 'secondary';
      case 'returned':
        return 'outline';
      case 'damaged':
        return 'destructive';
      default:
        return 'outline';
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t?.title ?? 'إدارة الأرقام التسلسلية و RFID'}</CardTitle>
        <CardDescription>{t?.description ?? 'إضافة وإدارة الأرقام التسلسلية و RFID للأصناف'}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="flex flex-wrap gap-3">
          <Button onClick={() => setShowBulkDialog(true)} size="sm">
            <PlusCircle className="me-2 h-4 w-4" />
            {t?.bulkAddButton ?? 'إدخال جماعي'}
          </Button>
          <Button onClick={() => setShowImportDialog(true)} size="sm" variant="outline">
            <Upload className="me-2 h-4 w-4" />
            {t?.importCSVButton ?? 'استيراد CSV'}
          </Button>
          <Button onClick={exportToCSV} size="sm" variant="outline">
            <Download className="me-2 h-4 w-4" />
            {t?.exportCSVButton ?? 'تصدير CSV'}
          </Button>
        </div>

        <div className="grid grid-cols-1 gap-3 md:grid-cols-4">
          <div className="space-y-1 rounded-md border bg-muted/20 p-3">
            <Label>{t?.searchLabel ?? 'بحث'}</Label>
            <div className="relative">
              <Search className="absolute right-2 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder={t?.searchPlaceholder ?? 'رقم تسلسلي، RFID، صنف...'}
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pe-8"
              />
            </div>
          </div>

          <div className="space-y-1 rounded-md border bg-muted/20 p-3">
            <Label>{t?.filterMaterialLabel ?? 'تصفية حسب الصنف'}</Label>
            <Select value={filterMaterialId} onValueChange={setFilterMaterialId}>
              <SelectTrigger>
                <SelectValue placeholder={t?.allMaterials ?? 'جميع الأصناف'} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="_all">{t?.allMaterials ?? 'جميع الأصناف'}</SelectItem>
                {selectableMaterials.map(m => (
                  <SelectItem key={m.id} value={m.id}>{m.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-1 rounded-md border bg-muted/20 p-3">
            <Label>{t?.filterStatusLabel ?? 'تصفية حسب الحالة'}</Label>
            <Select value={filterStatus} onValueChange={setFilterStatus}>
              <SelectTrigger>
                <SelectValue placeholder={t?.allStatuses ?? 'جميع الحالات'} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="_all">{t?.allStatuses ?? 'جميع الحالات'}</SelectItem>
                <SelectItem value="available">{t?.statusAvailable ?? 'متاح'}</SelectItem>
                <SelectItem value="in_stock">{t?.statusInStock ?? 'في المخزون'}</SelectItem>
                <SelectItem value="sold">{t?.statusSold ?? 'مباع'}</SelectItem>
                <SelectItem value="returned">{t?.statusReturned ?? 'مرتجع'}</SelectItem>
                <SelectItem value="damaged">{t?.statusDamaged ?? 'تالف'}</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-1 rounded-md border bg-muted/20 p-3">
            <Label>{t?.filterWarehouseLabel ?? 'تصفية حسب المستودع'}</Label>
            <Select value={filterWarehouseId} onValueChange={setFilterWarehouseId}>
              <SelectTrigger>
                <SelectValue placeholder={t?.allWarehouses ?? 'جميع المستودعات'} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="_all">{t?.allWarehouses ?? 'جميع المستودعات'}</SelectItem>
                {warehouses.map(w => (
                  <SelectItem key={w.id} value={w.id}>{w.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        {selectedUnits.size > 0 && (
          <div className="rounded-md border p-3 bg-muted/50 flex flex-wrap items-center gap-2">
            <span className="text-sm font-medium">
              {t?.selectedCount ?? 'محدد'}: {selectedUnits.size}
            </span>
            <div className="flex gap-2 ms-auto">
              <Button
                size="sm"
                variant="outline"
                onClick={() => handleBulkStatusChange('available')}
                disabled={isPending}
              >
                {t?.markAvailable ?? 'متاح'}
              </Button>
              <Button
                size="sm"
                variant="outline"
                onClick={() => handleBulkStatusChange('damaged')}
                disabled={isPending}
              >
                {t?.markDamaged ?? 'تالف'}
              </Button>
              <Button
                size="sm"
                variant="outline"
                onClick={() => setSelectedUnits(new Set())}
              >
                {t?.clearSelection ?? 'إلغاء التحديد'}
              </Button>
            </div>
          </div>
        )}

        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[50px]">
                  <input
                    type="checkbox"
                    checked={selectedUnits.size === filteredUnits.length && filteredUnits.length > 0}
                    onChange={toggleAllSelection}
                    className="h-4 w-4"
                  />
                </TableHead>
                <TableHead>{t?.serialNumberLabel ?? 'الرقم التسلسلي'}</TableHead>
                <TableHead>{t?.rfidCodeLabel ?? 'RFID'}</TableHead>
                <TableHead>{t?.materialLabel ?? 'الصنف'}</TableHead>
                <TableHead>{t?.status ?? 'الحالة'}</TableHead>
                <TableHead>{t?.warehouseLabel ?? 'المستودع'}</TableHead>
                <TableHead>{t?.location ?? 'الموقع'}</TableHead>
                <TableHead>{t?.createdAtLabel ?? 'تاريخ الإنشاء'}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredUnits.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={8} className="text-center text-muted-foreground h-24">
                    {t?.noUnits ?? 'لا توجد وحدات'}
                  </TableCell>
                </TableRow>
              ) : (
                filteredUnits.map(unit => {
                  const material = materials.find(m => m.id === unit.itemId);
                  const warehouse = warehouses.find(w => w.id === unit.warehouseId);
                  return (
                    <TableRow key={unit.id}>
                      <TableCell>
                        <input
                          type="checkbox"
                          checked={selectedUnits.has(unit.id)}
                          onChange={() => toggleUnitSelection(unit.id)}
                          className="h-4 w-4"
                        />
                      </TableCell>
                      <TableCell className="font-mono text-xs">
                        {(unit.serialNumber || '').trim() || '-'}
                      </TableCell>
                      <TableCell className="font-mono text-xs">
                        {(unit.rfidCode || '').trim() || '-'}
                      </TableCell>
                      <TableCell className="font-medium">
                        {material?.name || '-'}
                      </TableCell>
                      <TableCell>
                        <Badge variant={getStatusBadgeVariant(unit.status)}>
                          {unit.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {warehouse?.name || '-'}
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {(unit.location || '').trim() || '-'}
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {unit.createdAt ? formatDateStable(unit.createdAt) : '-'}
                      </TableCell>
                    </TableRow>
                  );
                })
              )}
            </TableBody>
          </Table>
        </div>

        <div className="text-sm text-muted-foreground">
          {t?.totalLabel ?? 'المجموع'}: {filteredUnits.length}
        </div>
      </CardContent>

      <Dialog open={showBulkDialog} onOpenChange={setShowBulkDialog}>
        <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{t?.bulkAddTitle ?? 'إدخال جماعي للأرقام التسلسلية / RFID'}</DialogTitle>
            <DialogDescription>{t?.bulkAddDescription ?? 'أدخل رقماً واحداً في كل سطر. إذا كان الصنف يحتوي Serial و RFID معاً، افصلهما بفاصلة.'}</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2 rounded-md border bg-muted/20 p-3">
              <Label>{t?.selectMaterialLabel ?? 'اختر الصنف'}</Label>
              <div className="relative">
                <Input
                  placeholder={t?.advancedSearchPlaceholder ?? 'بحث متقدم في جميع الأعمدة...'}
                  value={materialSearch}
                  onChange={(e) => {
                    setMaterialSearch(e.target.value);
                    setShowMaterialSuggestions(true);
                    if (!e.target.value.trim()) {
                      setSelectedMaterialId('');
                    }
                  }}
                  onFocus={() => setShowMaterialSuggestions(true)}
                  className="w-full sm:max-w-lg"
                />
                {showMaterialSuggestions && (
                  <div className="absolute z-50 mt-1 max-h-60 w-full overflow-auto rounded-md border bg-popover p-1 shadow-md">
                    {filteredTrackedMaterials.length === 0 ? (
                      <div className="px-2 py-1.5 text-xs text-muted-foreground">
                        {t?.noSearchResults ?? 'لا توجد نتائج مطابقة.'}
                      </div>
                    ) : (
                      filteredTrackedMaterials.map(m => (
                        <div
                          key={m.id}
                          className={`relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground ${
                            selectedMaterialId === m.id ? 'bg-accent' : ''
                          }`}
                          onClick={() => {
                            setSelectedMaterialId(m.id);
                            setMaterialSearch(m.name);
                            setShowMaterialSuggestions(false);
                          }}
                        >
                          <div className="flex-1">
                            <div className="font-medium">{m.name}</div>
                            <div className="text-xs text-muted-foreground">
                              {m.itemNumber || m.id}
                              {m.hasSerialNumber && m.hasRfid && ' • Serial + RFID'}
                              {m.hasSerialNumber && !m.hasRfid && ' • Serial'}
                              {!m.hasSerialNumber && m.hasRfid && ' • RFID'}
                            </div>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                )}
              </div>
              <p className="text-xs text-muted-foreground">
                {(t?.searchResultsCount ?? 'عدد النتائج')}: {filteredTrackedMaterials.length}
              </p>
              {selectedMaterial && (
                <div className="text-xs text-muted-foreground rounded-md bg-muted p-2">
                  {t?.selectedLabel ?? 'المحدد'}: <span className="font-medium">{selectedMaterial.name}</span>
                  {selectedMaterial.hasSerialNumber && selectedMaterial.hasRfid && ' (Serial + RFID)'}
                  {selectedMaterial.hasSerialNumber && !selectedMaterial.hasRfid && ' (Serial)'}
                  {!selectedMaterial.hasSerialNumber && selectedMaterial.hasRfid && ' (RFID)'}
                </div>
              )}
            </div>

            <div className="space-y-2 rounded-md border bg-muted/20 p-3">
              <Label>{t?.warehouseLabel ?? 'المستودع (اختياري)'}</Label>
              <Select value={selectedWarehouseId} onValueChange={setSelectedWarehouseId}>
                <SelectTrigger>
                  <SelectValue placeholder={t?.selectWarehousePlaceholder ?? 'اختر المستودع...'} />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="_none">{t?.noWarehouse ?? 'بدون مستودع'}</SelectItem>
                  {warehouses.map(w => (
                    <SelectItem key={w.id} value={w.id}>{w.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2 rounded-md border bg-muted/20 p-3">
              <Label>{t?.dataInputLabel ?? 'البيانات'}</Label>
              <Textarea
                placeholder={t?.bulkInputPlaceholder ?? 'SN001\nSN002\nأو:\nSN001,RFID001\nSN002,RFID002'}
                value={bulkInput}
                onChange={(e) => setBulkInput(e.target.value)}
                rows={12}
                className="font-mono text-sm"
              />
              <p className="text-xs text-muted-foreground">
                {t?.bulkInputHint ?? 'كل سطر = وحدة واحدة. استخدم الفاصلة (,) للفصل بين Serial و RFID'}
              </p>
            </div>
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                setShowBulkDialog(false);
                setBulkInput('');
                setSelectedMaterialId('');
                setMaterialSearch('');
                setShowMaterialSuggestions(false);
                setSelectedWarehouseId('_none');
              }}
            >
              {tGlobal?.cancel ?? 'إلغاء'}
            </Button>
            <Button onClick={handleBulkAdd} disabled={isPending}>
              {t?.addButton ?? 'إضافة'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showImportDialog} onOpenChange={setShowImportDialog}>
        <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{t?.importCSVTitle ?? 'استيراد من CSV'}</DialogTitle>
            <DialogDescription>
              {t?.importCSVDescription ?? 'الصق محتوى ملف CSV. السطر الأول يجب أن يحتوي على العناوين (serial,rfid) أو يمكن تجاوزه.'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2 rounded-md border bg-muted/20 p-3">
              <Label>{t?.selectMaterialLabel ?? 'اختر الصنف'}</Label>
              <div className="relative">
                <Input
                  placeholder={t?.advancedSearchPlaceholder ?? 'بحث متقدم في جميع الأعمدة...'}
                  value={materialSearch}
                  onChange={(e) => {
                    setMaterialSearch(e.target.value);
                    setShowMaterialSuggestions(true);
                    if (!e.target.value.trim()) {
                      setSelectedMaterialId('');
                    }
                  }}
                  onFocus={() => setShowMaterialSuggestions(true)}
                  className="w-full sm:max-w-lg"
                />
                {showMaterialSuggestions && (
                  <div className="absolute z-50 mt-1 max-h-60 w-full overflow-auto rounded-md border bg-popover p-1 shadow-md">
                    {filteredTrackedMaterials.length === 0 ? (
                      <div className="px-2 py-1.5 text-xs text-muted-foreground">
                        {t?.noSearchResults ?? 'لا توجد نتائج مطابقة.'}
                      </div>
                    ) : (
                      filteredTrackedMaterials.map(m => (
                        <div
                          key={m.id}
                          className={`relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground ${
                            selectedMaterialId === m.id ? 'bg-accent' : ''
                          }`}
                          onClick={() => {
                            setSelectedMaterialId(m.id);
                            setMaterialSearch(m.name);
                            setShowMaterialSuggestions(false);
                          }}
                        >
                          <div className="flex-1">
                            <div className="font-medium">{m.name}</div>
                            <div className="text-xs text-muted-foreground">
                              {m.itemNumber || m.id}
                              {m.hasSerialNumber && m.hasRfid && ' • Serial + RFID'}
                              {m.hasSerialNumber && !m.hasRfid && ' • Serial'}
                              {!m.hasSerialNumber && m.hasRfid && ' • RFID'}
                            </div>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                )}
              </div>
              <p className="text-xs text-muted-foreground">
                {(t?.searchResultsCount ?? 'عدد النتائج')}: {filteredTrackedMaterials.length}
              </p>
              {selectedMaterial && (
                <div className="text-xs text-muted-foreground rounded-md bg-muted p-2">
                  {t?.selectedLabel ?? 'المحدد'}: <span className="font-medium">{selectedMaterial.name}</span>
                  {selectedMaterial.hasSerialNumber && selectedMaterial.hasRfid && ' (Serial + RFID)'}
                  {selectedMaterial.hasSerialNumber && !selectedMaterial.hasRfid && ' (Serial)'}
                  {!selectedMaterial.hasSerialNumber && selectedMaterial.hasRfid && ' (RFID)'}
                </div>
              )}
            </div>

            <div className="space-y-2 rounded-md border bg-muted/20 p-3">
              <Label>{t?.warehouseLabel ?? 'المستودع (اختياري)'}</Label>
              <Select value={selectedWarehouseId} onValueChange={setSelectedWarehouseId}>
                <SelectTrigger>
                  <SelectValue placeholder={t?.selectWarehousePlaceholder ?? 'اختر المستودع...'} />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="_none">{t?.noWarehouse ?? 'بدون مستودع'}</SelectItem>
                  {warehouses.map(w => (
                    <SelectItem key={w.id} value={w.id}>{w.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2 rounded-md border bg-muted/20 p-3">
              <Label>{t?.csvContentLabel ?? 'محتوى CSV'}</Label>
              <Textarea
                placeholder="serial,rfid\nSN001,RFID001\nSN002,RFID002"
                value={csvInput}
                onChange={(e) => setCsvInput(e.target.value)}
                rows={12}
                className="font-mono text-sm"
              />
              <p className="text-xs text-muted-foreground">
                {t?.csvHint ?? 'الصيغة: serial,rfid (سطر لكل وحدة)'}
              </p>
            </div>

            <div className="rounded-md border p-3 bg-muted/50 text-xs space-y-1">
              <div className="font-medium">{t?.exampleLabel ?? 'مثال:'}</div>
              <pre className="text-muted-foreground">
{`serial,rfid
SN001,RFID001
SN002,RFID002
SN003,RFID003`}
              </pre>
            </div>
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                setShowImportDialog(false);
                setCsvInput('');
                setSelectedMaterialId('');
                setMaterialSearch('');
                setShowMaterialSuggestions(false);
                setSelectedWarehouseId('_none');
              }}
            >
              {tGlobal?.cancel ?? 'إلغاء'}
            </Button>
            <Button onClick={handleImportCSV} disabled={isPending}>
              {t?.importButton ?? 'استيراد'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </Card>
  );
}
