'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState, useTransition } from 'react';
import { useFieldArray, useForm, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { ArrowUpRight, PlusCircle, Loader2, Trash2 } from 'lucide-react';

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Textarea } from '@/components/ui/textarea';
import { handleCreateDisassemblyRecord } from '@/lib/actions';
import { formatCurrency } from '@/lib/currency-formatter';
import { formatDateDDMMYYYY } from '@/lib/utils';
import { useToast } from '@/hooks/use-toast';
import type { DisassemblyRecord, ProductionItem, StockLocationBalance, Warehouse } from '@/lib/types';

const disassemblyFormSchema = z.object({
  date: z.string().optional().default(''),
  parentItemId: z.string().min(1, 'Parent item is required.'),
  parentQuantity: z.coerce.number().min(0.0001, 'Parent quantity must be greater than zero.').default(1),
  purchaseCost: z.coerce.number().min(0).default(0),
  additionalCost: z.coerce.number().min(0).default(0),
  sourceWarehouseId: z.string().optional().default(''),
  sourceShelfId: z.string().optional().default(''),
  targetWarehouseId: z.string().optional().default(''),
  targetShelfId: z.string().optional().default(''),
  notes: z.string().optional().default(''),
  parts: z.array(z.object({
    partItemId: z.string().min(1, 'Part item is required.'),
    quantity: z.coerce.number().min(0.0001, 'Quantity must be greater than zero.'),
    expectedSalePrice: z.coerce.number().min(0).default(0),
    notes: z.string().optional().default(''),
  })).min(1, 'At least one output part is required.'),
});

type DisassemblyManagerProps = {
  materials: ProductionItem[];
  warehouses?: Warehouse[];
  warehousesEnabled?: boolean;
  stockLocationsByMaterial?: Record<string, StockLocationBalance[]>;
  records?: DisassemblyRecord[];
  t: any;
  tGlobal: any;
  currencySymbol?: string;
};

const getTodayValue = () => {
  const now = new Date();
  const local = new Date(now.getTime() - now.getTimezoneOffset() * 60000);
  return local.toISOString().slice(0, 10);
};

export default function DisassemblyManager({
  materials,
  warehouses = [],
  warehousesEnabled = false,
  stockLocationsByMaterial = {},
  records = [],
  t,
  tGlobal,
  currencySymbol = '$',
}: DisassemblyManagerProps) {
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();
  const [recordList, setRecordList] = useState<DisassemblyRecord[]>(records);
  const [tracePartId, setTracePartId] = useState('');

  const parentMaterials = useMemo(
    () => materials
      .filter((material) => material.isDisassemblable === true || (material.disassemblyTemplate || []).length > 0)
      .sort((left, right) => String(left.name || '').localeCompare(String(right.name || ''))),
    [materials],
  );

  const form = useForm<z.infer<typeof disassemblyFormSchema>>({
    resolver: zodResolver(disassemblyFormSchema),
    defaultValues: {
      date: getTodayValue(),
      parentItemId: '',
      parentQuantity: 1,
      purchaseCost: 0,
      additionalCost: 0,
      sourceWarehouseId: '',
      sourceShelfId: '',
      targetWarehouseId: '',
      targetShelfId: '',
      notes: '',
      parts: [],
    },
  });

  const { fields, append, remove, replace } = useFieldArray({
    control: form.control,
    name: 'parts',
  });

  const selectedParentId = useWatch({ control: form.control, name: 'parentItemId' });
  const watchedParts = useWatch({ control: form.control, name: 'parts' }) || [];
  const watchedParentQuantity = Number(useWatch({ control: form.control, name: 'parentQuantity' }) || 0);
  const watchedPurchaseCost = Number(useWatch({ control: form.control, name: 'purchaseCost' }) || 0);
  const watchedAdditionalCost = Number(useWatch({ control: form.control, name: 'additionalCost' }) || 0);
  const sourceWarehouseId = String(useWatch({ control: form.control, name: 'sourceWarehouseId' }) || '');
  const targetWarehouseId = String(useWatch({ control: form.control, name: 'targetWarehouseId' }) || '');

  const selectedParent = useMemo(
    () => parentMaterials.find((material) => String(material.id || '') === String(selectedParentId || '')),
    [parentMaterials, selectedParentId],
  );

  const partOptions = useMemo(
    () => materials
      .filter((material) => String(material.id || '') !== String(selectedParentId || ''))
      .sort((left, right) => String(left.name || '').localeCompare(String(right.name || ''))),
    [materials, selectedParentId],
  );

  useEffect(() => {
    if (!selectedParent) {
      replace([]);
      return;
    }

    const template = Array.isArray(selectedParent.disassemblyTemplate)
      ? selectedParent.disassemblyTemplate
          .filter((entry) => String(entry?.partItemId || '').trim())
          .map((entry) => ({
            partItemId: String(entry.partItemId || '').trim(),
            quantity: Number(entry.quantity || 1),
            expectedSalePrice: Number(entry.expectedSalePrice || 0),
            notes: String(entry.notes || ''),
          }))
      : [];

    replace(template);
  }, [selectedParent, replace]);

  const getShelvesForWarehouse = (warehouseId?: string) => {
    const warehouse = warehouses.find((entry) => String(entry.id || '') === String(warehouseId || ''));
    return warehouse?.shelves || [];
  };

  const sourceLocations = useMemo(
    () => stockLocationsByMaterial[String(selectedParentId || '')] || [],
    [stockLocationsByMaterial, selectedParentId],
  );

  const costPreviewRows = useMemo(() => {
    const totalSaleValue = watchedParts.reduce((sum, entry) => {
      const quantity = Number(entry?.quantity || 0);
      const expectedSalePrice = Number(entry?.expectedSalePrice || 0);
      if (!Number.isFinite(quantity) || quantity <= 0 || !Number.isFinite(expectedSalePrice) || expectedSalePrice < 0) return sum;
      return sum + (quantity * expectedSalePrice);
    }, 0);

    let remaining = watchedPurchaseCost + watchedAdditionalCost;

    return watchedParts.map((entry, index) => {
      const quantity = Number(entry?.quantity || 0);
      const expectedSalePrice = Number(entry?.expectedSalePrice || 0);
      const saleValue = quantity * expectedSalePrice;
      const isLast = index === watchedParts.length - 1;
      const allocatedCost = totalSaleValue > 0
        ? (isLast ? remaining : Math.round(((saleValue / totalSaleValue) * (watchedPurchaseCost + watchedAdditionalCost)) * 100) / 100)
        : 0;
      remaining = Math.round((remaining - allocatedCost) * 100) / 100;
      const costPerUnit = quantity > 0 ? allocatedCost / quantity : 0;
      const partMaterial = partOptions.find((material) => String(material.id || '') === String(entry?.partItemId || ''));

      return {
        partName: partMaterial?.name || String(entry?.partItemId || ''),
        saleValue,
        allocatedCost,
        costPerUnit,
      };
    });
  }, [watchedParts, watchedPurchaseCost, watchedAdditionalCost, partOptions]);

  const traceablePartOptions = useMemo(() => {
    const partIds = new Set<string>();
    recordList.forEach((record) => {
      (record.parts || []).forEach((part) => {
        const id = String(part.partItemId || '').trim();
        if (id) partIds.add(id);
      });
    });

    return materials
      .filter((material) => partIds.has(String(material.id || '').trim()))
      .sort((left, right) => String(left.name || '').localeCompare(String(right.name || '')));
  }, [recordList, materials]);

  const traceRows = useMemo(() => {
    return recordList.flatMap((record) => {
      return (record.parts || [])
        .filter((part) => !tracePartId || String(part.partItemId || '').trim() === tracePartId)
        .map((part) => ({
          recordId: record.id,
          date: record.date,
          recordNumber: record.recordNumber,
          parentItemId: record.parentItemId,
          parentItemName: record.parentItemName,
          parentQuantity: record.parentQuantity,
          partItemId: part.partItemId,
          partName: part.partName,
          quantity: part.quantity,
          allocatedCost: part.allocatedCost,
          costPerUnit: part.costPerUnit,
          notes: part.notes,
        }));
    }).sort((left, right) => String(right.date || '').localeCompare(String(left.date || '')));
  }, [recordList, tracePartId]);

  const onSubmit = (values: z.infer<typeof disassemblyFormSchema>) => {
    startTransition(async () => {
      const result = await handleCreateDisassemblyRecord(values);
      if (!result || 'error' in result) {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: (result as any)?.error || (t?.disassemblySaveError ?? 'تعذر حفظ مستند التفكيك.'),
          variant: 'destructive',
        });
        return;
      }

      const createdRecord = (result as any).record as DisassemblyRecord;
      setRecordList((prev) => [createdRecord, ...prev]);
      toast({
        title: tGlobal?.success ?? 'تم',
        description: t?.disassemblySaveSuccess ?? 'تم حفظ مستند التفكيك بنجاح.',
      });

      form.reset({
        date: getTodayValue(),
        parentItemId: values.parentItemId,
        parentQuantity: 1,
        purchaseCost: 0,
        additionalCost: 0,
        sourceWarehouseId: values.sourceWarehouseId || '',
        sourceShelfId: values.sourceShelfId || '',
        targetWarehouseId: values.targetWarehouseId || '',
        targetShelfId: values.targetShelfId || '',
        notes: '',
        parts: values.parts,
      });
    });
  };

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>{t?.disassemblyPageTitle ?? 'تفكيك الأصناف'}</CardTitle>
          <CardDescription>
            {t?.disassemblyPageDescription ?? 'حوّل الصنف الأب إلى عدة أجزاء مع توزيع التكلفة على الأجزاء تلقائياً بحسب أسعار البيع المرجعية.'}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
              <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                <FormField
                  control={form.control}
                  name="date"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.dateLabel ?? 'التاريخ'}</FormLabel>
                      <FormControl><Input type="date" {...field} value={field.value ?? ''} /></FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="parentItemId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.parentItemLabel ?? 'الصنف الأب'}</FormLabel>
                      <Select value={field.value || ''} onValueChange={field.onChange}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder={t?.parentItemPlaceholder ?? 'اختر الصنف المراد تفكيكه'} />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {parentMaterials.map((material) => (
                            <SelectItem key={material.id} value={material.id}>{material.name}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="parentQuantity"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.parentQuantityLabel ?? 'كمية الصنف الأب'}</FormLabel>
                      <FormControl><Input type="number" min="0.0001" step="0.01" {...field} /></FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="purchaseCost"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.purchaseCostLabel ?? 'تكلفة الأصل'}</FormLabel>
                      <FormControl><Input type="number" min="0" step="0.01" {...field} /></FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                <FormField
                  control={form.control}
                  name="additionalCost"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.additionalCostLabel ?? 'مصاريف التفكيك الإضافية'}</FormLabel>
                      <FormControl><Input type="number" min="0" step="0.01" {...field} /></FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {warehousesEnabled && (
                  <>
                    <FormField
                      control={form.control}
                      name="sourceWarehouseId"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.sourceWarehouseLabel ?? 'المستودع المصدر'}</FormLabel>
                          <Select value={field.value || ''} onValueChange={(value) => {
                            field.onChange(value);
                            form.setValue('sourceShelfId', '');
                          }}>
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder={t?.selectWarehousePlaceholder ?? 'اختر المستودع'} />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              {warehouses.map((warehouse) => (
                                <SelectItem key={warehouse.id} value={warehouse.id}>{warehouse.name}</SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="sourceShelfId"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.sourceShelfLabel ?? 'الرف المصدر'}</FormLabel>
                          <Select value={field.value || ''} onValueChange={field.onChange} disabled={!sourceWarehouseId}>
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder={t?.selectShelfPlaceholder ?? 'اختر الرف'} />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              {getShelvesForWarehouse(sourceWarehouseId).map((shelf) => (
                                <SelectItem key={shelf.id} value={shelf.id}>{shelf.name}</SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="targetWarehouseId"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.targetWarehouseLabel ?? 'المستودع الهدف للأجزاء'}</FormLabel>
                          <Select value={field.value || ''} onValueChange={(value) => {
                            field.onChange(value);
                            form.setValue('targetShelfId', '');
                          }}>
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder={t?.selectWarehousePlaceholder ?? 'اختر المستودع'} />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              {warehouses.map((warehouse) => (
                                <SelectItem key={warehouse.id} value={warehouse.id}>{warehouse.name}</SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="targetShelfId"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.targetShelfLabel ?? 'الرف الهدف للأجزاء'}</FormLabel>
                          <Select value={field.value || ''} onValueChange={field.onChange} disabled={!targetWarehouseId}>
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder={t?.selectShelfPlaceholder ?? 'اختر الرف'} />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              {getShelvesForWarehouse(targetWarehouseId).map((shelf) => (
                                <SelectItem key={shelf.id} value={shelf.id}>{shelf.name}</SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </>
                )}
              </div>

              {selectedParent && (
                <div className="rounded-md border bg-muted/20 p-3 text-sm">
                  <div className="font-medium">{selectedParent.name}</div>
                  <div className="text-muted-foreground mt-1">
                    {t?.currentSalePriceLabel ?? 'سعر البيع الحالي'}: {formatCurrency(Number(selectedParent.salePrice || 0), currencySymbol)}
                  </div>
                  {sourceLocations.length > 0 && (
                    <div className="mt-2 text-xs text-muted-foreground">
                      {t?.availableStockByShelf ?? 'الرصيد الحالي حسب الرف'}:{' '}
                      {sourceLocations.map((location) => `${location.warehouseName} / ${location.shelfName}: ${location.quantity}`).join(' — ')}
                    </div>
                  )}
                </div>
              )}

              <div className="space-y-3 rounded-md border p-3">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <div>
                    <p className="font-medium">{t?.disassemblyOutputsTitle ?? 'الأجزاء الناتجة'}</p>
                    <p className="text-xs text-muted-foreground">
                      {t?.disassemblyOutputsDescription ?? 'يمكنك تعديل الكميات الفعلية والأسعار المرجعية قبل الحفظ.'}
                    </p>
                  </div>
                  <Button type="button" variant="outline" size="sm" onClick={() => append({ partItemId: '', quantity: watchedParentQuantity || 1, expectedSalePrice: 0, notes: '' })}>
                    <PlusCircle className="me-2 h-4 w-4" />
                    {t?.addPartButton ?? 'إضافة جزء'}
                  </Button>
                </div>

                <div className="rounded-md border overflow-hidden">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>{t?.partItemLabel ?? 'الجزء'}</TableHead>
                        <TableHead>{t?.quantityLabel ?? 'الكمية'}</TableHead>
                        <TableHead>{t?.expectedSalePriceLabel ?? 'سعر البيع المرجعي'}</TableHead>
                        <TableHead>{t?.allocatedCostLabel ?? 'التكلفة الموزعة'}</TableHead>
                        <TableHead>{t?.costPerUnitLabel ?? 'تكلفة الوحدة'}</TableHead>
                        <TableHead>{t?.notesLabel ?? 'ملاحظات'}</TableHead>
                        <TableHead className="w-[60px]"></TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {fields.length === 0 && (
                        <TableRow>
                          <TableCell colSpan={7} className="h-20 text-center text-muted-foreground">
                            {t?.noDisassemblyParts ?? 'لا توجد أجزاء في هذا القالب بعد.'}
                          </TableCell>
                        </TableRow>
                      )}
                      {fields.map((fieldRow, index) => (
                        <TableRow key={fieldRow.id}>
                          <TableCell>
                            <FormField
                              control={form.control}
                              name={`parts.${index}.partItemId`}
                              render={({ field }) => (
                                <FormItem>
                                  <Select value={field.value || ''} onValueChange={field.onChange}>
                                    <FormControl>
                                      <SelectTrigger>
                                        <SelectValue placeholder={t?.selectPartPlaceholder ?? 'اختر الجزء'} />
                                      </SelectTrigger>
                                    </FormControl>
                                    <SelectContent>
                                      {partOptions.map((material) => (
                                        <SelectItem key={`${material.id}-${index}`} value={material.id}>{material.name}</SelectItem>
                                      ))}
                                    </SelectContent>
                                  </Select>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                          </TableCell>
                          <TableCell>
                            <FormField
                              control={form.control}
                              name={`parts.${index}.quantity`}
                              render={({ field }) => (
                                <FormItem>
                                  <FormControl><Input type="number" min="0.0001" step="0.01" {...field} /></FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                          </TableCell>
                          <TableCell>
                            <FormField
                              control={form.control}
                              name={`parts.${index}.expectedSalePrice`}
                              render={({ field }) => (
                                <FormItem>
                                  <FormControl><Input type="number" min="0" step="0.01" {...field} /></FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                          </TableCell>
                          <TableCell>{formatCurrency(costPreviewRows[index]?.allocatedCost || 0, currencySymbol)}</TableCell>
                          <TableCell>{formatCurrency(costPreviewRows[index]?.costPerUnit || 0, currencySymbol)}</TableCell>
                          <TableCell>
                            <FormField
                              control={form.control}
                              name={`parts.${index}.notes`}
                              render={({ field }) => (
                                <FormItem>
                                  <FormControl><Input {...field} value={field.value ?? ''} placeholder={t?.notesPlaceholder ?? 'ملاحظات'} /></FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                          </TableCell>
                          <TableCell className="text-right">
                            <Button type="button" variant="ghost" size="icon" onClick={() => remove(index)}>
                              <Trash2 className="h-4 w-4 text-destructive" />
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              </div>

              <FormField
                control={form.control}
                name="notes"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t?.notesLabel ?? 'ملاحظات'}</FormLabel>
                    <FormControl>
                      <Textarea {...field} value={field.value ?? ''} placeholder={t?.disassemblyNotesPlaceholder ?? 'ملاحظات على عملية التفكيك أو حالة الصنف الأصلي'} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="rounded-md border bg-muted/20 p-3 text-sm">
                <div>{t?.totalDisassemblyCostLabel ?? 'إجمالي تكلفة التفكيك'}: <span className="font-medium">{formatCurrency(watchedPurchaseCost + watchedAdditionalCost, currencySymbol)}</span></div>
                <div className="mt-1 text-muted-foreground">{t?.disassemblyTraceabilityHint ?? 'سيتم ربط كل جزء بمستند التفكيك وبالصنف الأب، ويمكن أن يأتي نفس الجزء من أكثر من صنف أب عبر الزمن.'}</div>
              </div>

              <Button type="submit" disabled={isPending}>
                {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                {t?.saveDisassemblyButton ?? 'حفظ مستند التفكيك'}
              </Button>
            </form>
          </Form>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>{t?.disassemblyHistoryTitle ?? 'سجل التفكيك'}</CardTitle>
          <CardDescription>{t?.disassemblyHistoryDescription ?? 'يوضح كل عمليات التفكيك السابقة ومصدر الأجزاء الناتجة.'}</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="rounded-md border overflow-hidden">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{t?.dateLabel ?? 'التاريخ'}</TableHead>
                  <TableHead>{t?.referenceLabel ?? 'المرجع'}</TableHead>
                  <TableHead>{t?.parentItemLabel ?? 'الصنف الأب'}</TableHead>
                  <TableHead>{t?.partsCountLabel ?? 'عدد الأجزاء'}</TableHead>
                  <TableHead>{t?.totalCostLabel ?? 'التكلفة'}</TableHead>
                  <TableHead>{t?.detailsLabel ?? 'التفاصيل'}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {recordList.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={6} className="h-20 text-center text-muted-foreground">
                      {t?.noDisassemblyRecords ?? 'لا توجد عمليات تفكيك مسجلة بعد.'}
                    </TableCell>
                  </TableRow>
                )}
                {recordList.map((record) => (
                  <TableRow key={record.id}>
                    <TableCell>{formatDateDDMMYYYY(record.date)}</TableCell>
                    <TableCell>{record.recordNumber}</TableCell>
                    <TableCell>{record.parentItemName}</TableCell>
                    <TableCell>{record.parts.length}</TableCell>
                    <TableCell>{formatCurrency(record.totalCostAllocated || 0, currencySymbol)}</TableCell>
                    <TableCell className="text-xs text-muted-foreground">
                      <div className="space-y-2">
                        <div>
                          {record.parts.slice(0, 3).map((part) => `${part.partName} (${part.quantity}) - ${formatCurrency(part.costPerUnit || 0, currencySymbol)}`).join('، ')}
                          {record.parts.length > 3 ? ' ...' : ''}
                        </div>
                        <Button asChild type="button" variant="link" size="sm" className="h-auto p-0 text-xs">
                          <Link href={`/admin/data/material-movements?sourceParentItemId=${encodeURIComponent(record.parentItemId)}&referenceType=disassembly`}>
                            {t?.openSourceMovementsButton ?? 'عرض حركة الأجزاء'}
                            <ArrowUpRight className="h-3.5 w-3.5" />
                          </Link>
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>{t?.disassemblyTraceabilityTitle ?? 'تتبع مصادر الجزء'}</CardTitle>
          <CardDescription>
            {t?.disassemblyTraceabilityDescription ?? 'اختر جزءاً لمعرفة كل الأصناف الأب ومستندات التفكيك التي أنتجته، حتى لو كان الجزء نفسه يأتي من عدة أصناف مختلفة.'}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="max-w-md space-y-2">
            <Label>{t?.partItemLabel ?? 'الجزء'}</Label>
            <Select value={tracePartId || 'all'} onValueChange={(value) => setTracePartId(value === 'all' ? '' : value)}>
              <SelectTrigger>
                <SelectValue placeholder={t?.selectPartPlaceholder ?? 'اختر الجزء'} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">{t?.allItemsOption ?? 'كل الأصناف'}</SelectItem>
                {traceablePartOptions.map((material) => (
                  <SelectItem key={material.id} value={material.id}>{material.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="rounded-md border overflow-hidden">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{t?.dateLabel ?? 'التاريخ'}</TableHead>
                  <TableHead>{t?.referenceLabel ?? 'المرجع'}</TableHead>
                  <TableHead>{t?.parentItemLabel ?? 'الصنف الأب'}</TableHead>
                  <TableHead>{t?.partItemLabel ?? 'الجزء'}</TableHead>
                  <TableHead>{t?.quantityLabel ?? 'الكمية'}</TableHead>
                  <TableHead>{t?.allocatedCostLabel ?? 'التكلفة الموزعة'}</TableHead>
                  <TableHead>{t?.costPerUnitLabel ?? 'تكلفة الوحدة'}</TableHead>
                  <TableHead>{t?.notesLabel ?? 'ملاحظات'}</TableHead>
                  <TableHead>{t?.openDetailsLabel ?? 'فتح'}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {traceRows.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={9} className="h-20 text-center text-muted-foreground">
                      {t?.noTraceabilityRows ?? 'لا توجد سجلات مصدر مطابقة للجزء المحدد.'}
                    </TableCell>
                  </TableRow>
                ) : (
                  traceRows.map((row) => (
                    <TableRow key={`${row.recordId}-${row.parentItemId}-${row.partItemId}-${row.quantity}`}>
                      <TableCell>{formatDateDDMMYYYY(row.date)}</TableCell>
                      <TableCell>{row.recordNumber}</TableCell>
                      <TableCell>{row.parentItemName} ({row.parentQuantity})</TableCell>
                      <TableCell>{row.partName}</TableCell>
                      <TableCell>{row.quantity}</TableCell>
                      <TableCell>{formatCurrency(row.allocatedCost || 0, currencySymbol)}</TableCell>
                      <TableCell>{formatCurrency(row.costPerUnit || 0, currencySymbol)}</TableCell>
                      <TableCell>{row.notes || '-'}</TableCell>
                      <TableCell className="whitespace-nowrap">
                        <Button asChild type="button" variant="outline" size="sm">
                          <Link href={`/admin/data/material-movements?materialId=${encodeURIComponent(row.partItemId)}&sourceParentItemId=${encodeURIComponent(row.parentItemId)}&referenceType=disassembly`}>
                            {t?.filterMovementsButton ?? 'عرض الحركة'}
                            <ArrowUpRight className="h-3.5 w-3.5" />
                          </Link>
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
