'use client';

import { useEffect, useMemo, useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
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 { useToast } from '@/hooks/use-toast';
import { useDocumentLock } from '@/hooks/use-document-lock';
import {
  handleAddWarehouse,
  handleDeleteWarehouse,
  handleGenerateShelves,
  handleAddShelf,
  handleUpdateShelf,
  handleDeleteShelf,
  handleToggleWarehouseActive,
  handleToggleShelfActive,
} from '@/lib/actions';
import type { Warehouse, Shelf } from '@/lib/types';
import { Pencil, Printer, Trash2 } from 'lucide-react';
import { ShelfLabelPrint } from '@/components/admin/shelf-label-print';
import { DocumentLockBanner } from '@/components/admin/document-lock-banner';

const warehouseSchema = z.object({
  name: z.string().min(2, 'Warehouse name is required.'),
  branchName: z.string().optional().default(''),
  departmentsText: z.string().optional().default(''),
  warehouseType: z.enum(['main', 'branch', 'returns', 'transit']).default('branch'),
  managerEmployeeId: z.string().optional().default(''),
  managerName: z.string().optional().default(''),
  operatingStatus: z.enum(['active', 'stopped', 'inventory']).default('active'),
  city: z.string().optional().default(''),
  address: z.string().optional().default(''),
  contactPhone: z.string().optional().default(''),
  allowIssueWithoutStock: z.enum(['yes', 'no']).default('no'),
  useInPos: z.enum(['yes', 'no']).default('yes'),
  location: z.string().optional().default(''),
  notes: z.string().optional().default(''),
});

type WarehouseValues = z.infer<typeof warehouseSchema>;

const shelfSchema = z.object({
  name: z.string().min(1, 'Shelf name is required.'),
  notes: z.string().optional().default(''),
});

type ShelfValues = z.infer<typeof shelfSchema>;

const generateShelvesSchema = z.object({
  prefix: z.string().optional(),
  separator: z.string().optional(),
  startNumber: z.coerce.number().int().min(0).optional(),
  count: z.coerce.number().int().min(1).max(500),
});

type GenerateShelvesValues = z.infer<typeof generateShelvesSchema>;

function upsertWarehouse(list: Warehouse[], nextWarehouse: Warehouse): Warehouse[] {
  const next = list.map((warehouse) => (warehouse.id === nextWarehouse.id ? nextWarehouse : warehouse));
  if (next.some((warehouse) => warehouse.id === nextWarehouse.id)) return next;
  return [...list, nextWarehouse];
}

function getWarehouseStatus(warehouse: Warehouse): 'active' | 'stopped' | 'inventory' {
  if (warehouse.operatingStatus) return warehouse.operatingStatus;
  return warehouse.inactive ? 'stopped' : 'active';
}

export default function WarehouseShelfManager({
  warehouses,
  employees,
  branchOptions,
  t,
  tGlobal,
}: {
  warehouses: Warehouse[];
  employees: Array<{ id: string; name: string }>;
  branchOptions: string[];
  t: any;
  tGlobal: any;
}) {
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();
  const [localWarehouses, setLocalWarehouses] = useState<Warehouse[]>(warehouses);
  const [warehouseSearch, setWarehouseSearch] = useState('');
  const [shelfSearch, setShelfSearch] = useState('');
  const [activeWarehouseId, setActiveWarehouseId] = useState<string | null>(null);
  const [isShelvesDialogOpen, setIsShelvesDialogOpen] = useState(false);
  const [editingShelf, setEditingShelf] = useState<Shelf | null>(null);
  const { lockStatus } = useDocumentLock('shelf', editingShelf?.id || '', { enabled: isShelvesDialogOpen && !!editingShelf?.id });
  const isShelfEditLocked = isShelvesDialogOpen && !!editingShelf && lockStatus.isLocked;

  useEffect(() => {
    setLocalWarehouses(warehouses);
  }, [warehouses]);

  const activeWarehouse = useMemo(
    () => localWarehouses.find((wh) => wh.id === activeWarehouseId) || null,
    [localWarehouses, activeWarehouseId]
  );

  const sortedWarehouses = useMemo(
    () => [...localWarehouses].sort((a, b) => String(a.warehouseNumber || '').localeCompare(String(b.warehouseNumber || ''))),
    [localWarehouses]
  );

  const filteredWarehouses = useMemo(() => {
    const query = warehouseSearch.trim().toLowerCase();
    if (!query) return sortedWarehouses;
    return sortedWarehouses.filter((warehouse) => (
      [
        warehouse.warehouseNumber,
        warehouse.name,
        warehouse.branchName,
        warehouse.warehouseType,
        warehouse.operatingStatus,
        warehouse.managerName,
        warehouse.city,
        warehouse.address,
        warehouse.contactPhone,
        warehouse.location,
        warehouse.notes,
        Array.isArray(warehouse.departments) ? warehouse.departments.join(' ') : '',
      ]
        .filter(Boolean)
        .some((value) => String(value).toLowerCase().includes(query))
    ));
  }, [sortedWarehouses, warehouseSearch]);

  const shelvesSorted = useMemo(() => {
    if (!activeWarehouse) return [] as Shelf[];
    return [...(activeWarehouse.shelves || [])].sort((a, b) => a.sequence - b.sequence);
  }, [activeWarehouse]);

  const filteredShelves = useMemo(() => {
    const query = shelfSearch.trim().toLowerCase();
    if (!query) return shelvesSorted;
    return shelvesSorted.filter((shelf) => (
      [shelf.shelfNumber, shelf.name, shelf.notes, shelf.sequence]
        .filter((value) => value !== undefined && value !== null)
        .some((value) => String(value).toLowerCase().includes(query))
    ));
  }, [shelvesSorted, shelfSearch]);

  const router = useRouter();
  const addWarehouseForm = useForm<WarehouseValues>({
    resolver: zodResolver(warehouseSchema),
    defaultValues: { name: '', branchName: '', departmentsText: '', warehouseType: 'branch', managerEmployeeId: '', managerName: '', operatingStatus: 'active', city: '', address: '', contactPhone: '', allowIssueWithoutStock: 'no', useInPos: 'yes', location: '', notes: '' },
  });



  const shelfForm = useForm<ShelfValues>({
    resolver: zodResolver(shelfSchema),
    defaultValues: { name: '', notes: '' },
  });

  const generateShelvesForm = useForm<GenerateShelvesValues>({
    resolver: zodResolver(generateShelvesSchema),
    defaultValues: {
      prefix: 'A',
      separator: '-',
      startNumber: 1,
      count: 10,
    },
  });

  const openShelvesDialog = (warehouseId: string) => {
    setActiveWarehouseId(warehouseId);
    setEditingShelf(null);
    setShelfSearch('');
    shelfForm.reset({ name: '', notes: '' });
    setIsShelvesDialogOpen(true);
  };



  const handleAddWarehouseSubmit = (values: WarehouseValues) => {
    startTransition(async () => {
      const departments = String(values.departmentsText || '')
        .split(',')
        .map((entry) => entry.trim())
        .filter(Boolean);
      const result = await handleAddWarehouse({
        ...values,
        departments,
        allowIssueWithoutStock: values.allowIssueWithoutStock === 'yes',
        useInPos: values.useInPos === 'yes',
      });
      if (result && 'success' in result && result.success && result.item) {
        setLocalWarehouses((prev) => upsertWarehouse(prev, result.item as Warehouse));
        addWarehouseForm.reset({ name: '', branchName: '', departmentsText: '', warehouseType: 'branch', managerEmployeeId: '', managerName: '', operatingStatus: 'active', city: '', address: '', contactPhone: '', allowIssueWithoutStock: 'no', useInPos: 'yes', location: '', notes: '' });
        toast({ title: t?.warehouseAddedSuccess ?? 'تمت إضافة المستودع بنجاح' });
        return;
      }
      toast({
        title: t?.saveErrorTitle ?? tGlobal?.error ?? 'Error',
        description: result?.error || t?.warehouseAddError || 'Failed to add warehouse',
        variant: 'destructive',
      });
    });
  };



  const onDeleteWarehouse = (warehouse: Warehouse) => {
    const confirmed = typeof window !== 'undefined' ? window.confirm((t?.warehouseDeleteConfirm ?? 'هل تريد حذف المستودع {name}؟').replace('{name}', warehouse.name)) : true;
    if (!confirmed) return;
    startTransition(async () => {
      const result = await handleDeleteWarehouse(warehouse.id);
      if (result && 'success' in result && result.success) {
        setLocalWarehouses((prev) => prev.filter((entry) => entry.id !== warehouse.id));
        if (activeWarehouseId === warehouse.id) {
          setActiveWarehouseId(null);
          setIsShelvesDialogOpen(false);
        }
        toast({ title: t?.warehouseDeletedSuccess ?? 'تم حذف المستودع بنجاح' });
        return;
      }
      toast({
        title: t?.saveErrorTitle ?? tGlobal?.error ?? 'Error',
        description: result?.error || t?.warehouseDeleteError || 'Failed to delete warehouse',
        variant: 'destructive',
      });
    });
  };

  const handleShelfSubmit = (values: ShelfValues) => {
    if (!activeWarehouse) return;
    if (isShelfEditLocked) return;

    startTransition(async () => {
      const result = editingShelf
        ? await handleUpdateShelf(activeWarehouse.id, editingShelf.id, values)
        : await handleAddShelf(activeWarehouse.id, values);

      if (result && 'success' in result && result.success && result.item) {
        const shelf = result.item as Shelf;
        setLocalWarehouses((prev) => prev.map((warehouse) => {
          if (warehouse.id !== activeWarehouse.id) return warehouse;
          const shelves = Array.isArray(warehouse.shelves) ? [...warehouse.shelves] : [];
          const index = shelves.findIndex((entry) => entry.id === shelf.id);
          if (index >= 0) shelves[index] = shelf;
          else shelves.push(shelf);
          return { ...warehouse, shelves };
        }));
        setEditingShelf(null);
        shelfForm.reset({ name: '', notes: '' });
        toast({ title: editingShelf ? (t?.shelfUpdatedSuccess ?? 'تم تحديث الرف بنجاح') : (t?.shelfAddedSuccess ?? 'تمت إضافة الرف بنجاح') });
        return;
      }

      toast({
        title: t?.saveErrorTitle ?? tGlobal?.error ?? 'Error',
        description: result?.error || (editingShelf ? (t?.shelfUpdateError ?? 'Failed to update shelf') : (t?.shelfAddError ?? 'Failed to add shelf')),
        variant: 'destructive',
      });
    });
  };

  const onEditShelf = (shelf: Shelf) => {
    setEditingShelf(shelf);
    shelfForm.reset({ name: shelf.name || '', notes: shelf.notes || '' });
  };

  const onDeleteShelf = (shelf: Shelf) => {
    if (!activeWarehouse) return;
    const confirmed = typeof window !== 'undefined' ? window.confirm((t?.shelfDeleteConfirm ?? 'هل تريد حذف الرف {name}؟').replace('{name}', shelf.name)) : true;
    if (!confirmed) return;

    startTransition(async () => {
      const result = await handleDeleteShelf(activeWarehouse.id, shelf.id);
      if (result && 'success' in result && result.success) {
        setLocalWarehouses((prev) => prev.map((warehouse) => {
          if (warehouse.id !== activeWarehouse.id) return warehouse;
          return { ...warehouse, shelves: (warehouse.shelves || []).filter((entry) => entry.id !== shelf.id) };
        }));
        if (editingShelf?.id === shelf.id) {
          setEditingShelf(null);
          shelfForm.reset({ name: '', notes: '' });
        }
        toast({ title: t?.shelfDeletedSuccess ?? 'تم حذف الرف بنجاح' });
        return;
      }

      toast({
        title: t?.saveErrorTitle ?? tGlobal?.error ?? 'Error',
        description: result?.error || t?.shelfDeleteError || 'Failed to delete shelf',
        variant: 'destructive',
      });
    });
  };

  const handleGenerateShelvesSubmit = (values: GenerateShelvesValues) => {
    if (!activeWarehouse) return;
    const payload = {
      ...values,
      prefix: String(values.prefix || '').trim(),
      separator: String(values.separator || ''),
      startNumber: Number.isFinite(values.startNumber) ? Number(values.startNumber) : 1,
    };

    startTransition(async () => {
      const result = await handleGenerateShelves(activeWarehouse.id, payload);
      const response = result as { success?: boolean; added?: Shelf[]; skipped?: string[]; error?: string } | undefined;
      if (response?.success) {
        const added = response.added || [];
        const skipped = response.skipped || [];
        setLocalWarehouses((prev) => prev.map((warehouse) => {
          if (warehouse.id !== activeWarehouse.id) return warehouse;
          return {
            ...warehouse,
            shelves: [...(warehouse.shelves || []), ...added],
          };
        }));
        toast({
          title: t?.shelvesAddedSuccess ?? 'تمت إضافة الرفوف بنجاح',
          description: skipped.length > 0
            ? (t?.shelvesSkippedWarning ?? 'تم تجاوز الأسماء المكررة: {names}').replace('{names}', skipped.slice(0, 5).join(', '))
            : undefined,
        });
        return;
      }

      toast({
        title: t?.saveErrorTitle ?? tGlobal?.error ?? 'Error',
        description: response?.error || t?.shelvesAddError || 'Failed to add shelves',
        variant: 'destructive',
      });
    });
  };

  return (
    <>
      <Card>
        <CardHeader>
          <CardTitle>{t?.warehousesTitle ?? 'الفروع و المستودعات'}</CardTitle>
          <CardDescription>{t?.warehousesDescription ?? 'إدارة المستودعات والرفوف المرتبطة بها.'}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="rounded-lg border p-4 space-y-4">
            <div>
              <p className="text-sm font-medium">{t?.warehouseCreateSection ?? 'إضافة مستودع جديد'}</p>
              <p className="text-xs text-muted-foreground">{t?.warehouseReferenceHint ?? 'يتم توليد مرجع ثابت وفريد لكل مستودع، ويبقى كما هو حتى عند تعديل الاسم.'}</p>
            </div>
            <Form {...addWarehouseForm}>
              <form onSubmit={addWarehouseForm.handleSubmit(handleAddWarehouseSubmit)} className="grid gap-3 md:grid-cols-3">
                <FormField
                  control={addWarehouseForm.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.warehouseNameLabel ?? 'اسم المستودع'}</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder={t?.warehouseNamePlaceholder ?? 'مثال: المستودع الرئيسي'} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={addWarehouseForm.control}
                  name="branchName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.branchLabel ?? 'الفرع'}</FormLabel>
                      <Select value={field.value && field.value.length > 0 ? field.value : 'none'} onValueChange={(value) => field.onChange(value === 'none' ? '' : value)}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder={t?.branchPlaceholder ?? 'اختر الفرع'} />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="none">{t?.select ?? 'غير محدد'}</SelectItem>
                          {branchOptions.map((branch) => (
                            <SelectItem key={branch} value={branch}>{branch}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={addWarehouseForm.control}
                  name="departmentsText"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.departmentsLabel ?? 'الأقسام التابعة'}</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder={t?.departmentsPlaceholder ?? 'مثال: مبيعات, مشتريات, تشغيل'} />
                      </FormControl>
                      <p className="text-xs text-muted-foreground">{t?.departmentsHint ?? 'افصل بين الأقسام بفاصلة (,).'}</p>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={addWarehouseForm.control}
                  name="warehouseType"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.warehouseTypeLabel ?? 'نوع المستودع'}</FormLabel>
                      <Select value={field.value} onValueChange={field.onChange}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="main">{t?.warehouseTypeMain ?? 'رئيسي'}</SelectItem>
                          <SelectItem value="branch">{t?.warehouseTypeBranch ?? 'فرعي'}</SelectItem>
                          <SelectItem value="returns">{t?.warehouseTypeReturns ?? 'مرتجعات'}</SelectItem>
                          <SelectItem value="transit">{t?.warehouseTypeTransit ?? 'انتقالي'}</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={addWarehouseForm.control}
                  name="managerEmployeeId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.warehouseManagerLabel ?? 'مسؤول المستودع'}</FormLabel>
                      <Select value={field.value && field.value.length > 0 ? field.value : 'none'} onValueChange={(value) => field.onChange(value === 'none' ? '' : value)}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder={t?.warehouseManagerPlaceholder ?? 'اختر المسؤول'} />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="none">{t?.select ?? 'غير محدد'}</SelectItem>
                          {employees.map((employee) => (
                            <SelectItem key={employee.id} value={employee.id}>{employee.name}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={addWarehouseForm.control}
                  name="operatingStatus"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.warehouseOperatingStatusLabel ?? 'حالة التشغيل'}</FormLabel>
                      <Select value={field.value} onValueChange={field.onChange}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="active">{t?.warehouseStatusActive ?? 'نشط'}</SelectItem>
                          <SelectItem value="stopped">{t?.warehouseStatusStopped ?? 'موقوف'}</SelectItem>
                          <SelectItem value="inventory">{t?.warehouseStatusInventory ?? 'تحت الجرد'}</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={addWarehouseForm.control}
                  name="city"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.warehouseCityLabel ?? 'المدينة'}</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder={t?.warehouseCityPlaceholder ?? 'مثال: عمّان'} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={addWarehouseForm.control}
                  name="address"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.warehouseAddressLabel ?? 'العنوان'}</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder={t?.warehouseAddressPlaceholder ?? 'العنوان التفصيلي'} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={addWarehouseForm.control}
                  name="contactPhone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.warehouseContactPhoneLabel ?? 'رقم التواصل'}</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder={t?.warehouseContactPhonePlaceholder ?? 'مثال: 09xxxxxxxx'} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={addWarehouseForm.control}
                  name="allowIssueWithoutStock"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.allowIssueWithoutStockLabel ?? 'يسمح بالصرف بدون رصيد'}</FormLabel>
                      <Select value={field.value} onValueChange={field.onChange}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="yes">{t?.yesLabel ?? 'نعم'}</SelectItem>
                          <SelectItem value="no">{t?.noLabel ?? 'لا'}</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={addWarehouseForm.control}
                  name="useInPos"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.warehouseUseInPosLabel ?? 'استخدامه في POS'}</FormLabel>
                      <Select value={field.value} onValueChange={field.onChange}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="yes">{t?.yesLabel ?? 'نعم'}</SelectItem>
                          <SelectItem value="no">{t?.noLabel ?? 'لا'}</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={addWarehouseForm.control}
                  name="notes"
                  render={({ field }) => (
                    <FormItem className="md:col-span-3">
                      <FormLabel>{t?.notesLabel ?? 'ملاحظات'}</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder={t?.warehouseNotesPlaceholder ?? 'أي وصف إضافي'} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <div className="md:col-span-3 flex justify-end">
                  <Button type="submit" disabled={isPending}>
                    {t?.addWarehouseButton ?? 'إضافة مستودع'}
                  </Button>
                </div>
              </form>
            </Form>
          </div>

          <div className="flex justify-end">
            <Input
              value={warehouseSearch}
              onChange={(event) => setWarehouseSearch(event.target.value)}
              placeholder={t?.warehouseSearchPlaceholder ?? 'ابحث بالمرجع أو الاسم أو الموقع...'}
              className="w-full md:max-w-sm"
            />
          </div>

          <div className="rounded-md border overflow-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{t?.warehouseReferenceLabel ?? 'مرجع المستودع'}</TableHead>
                  <TableHead>{t?.warehouseNameLabel ?? 'اسم المستودع'}</TableHead>
                  <TableHead>{t?.branchLabel ?? 'الفرع'}</TableHead>
                  <TableHead>{t?.departmentsLabel ?? 'الأقسام التابعة'}</TableHead>
                  <TableHead>{t?.warehouseLocationLabel ?? 'الموقع'}</TableHead>
                  <TableHead className="text-center">{t?.shelvesCountLabel ?? 'عدد الرفوف'}</TableHead>
                  <TableHead>{t?.notesLabel ?? 'ملاحظات'}</TableHead>
                  <TableHead className="text-center">{t?.statusLabel ?? 'الحالة'}</TableHead>
                  <TableHead className="text-right">{tGlobal?.actions ?? 'إجراءات'}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredWarehouses.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={9} className="h-20 text-center text-muted-foreground">
                      {t?.noWarehousesFound ?? 'لا توجد مستودعات بعد.'}
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredWarehouses.map((warehouse) => (
                    <TableRow key={warehouse.id}>
                      <TableCell className="font-mono text-xs">{warehouse.warehouseNumber || '-'}</TableCell>
                      <TableCell className="font-medium">{warehouse.name}</TableCell>
                      <TableCell>{warehouse.branchName || '-'}</TableCell>
                      <TableCell className="max-w-[220px] truncate">{Array.isArray(warehouse.departments) && warehouse.departments.length > 0 ? warehouse.departments.join('، ') : '-'}</TableCell>
                      <TableCell>{warehouse.address || warehouse.location || '-'}</TableCell>
                      <TableCell className="text-center">{warehouse.shelves?.length ?? 0}</TableCell>
                      <TableCell className="max-w-[220px] truncate">{warehouse.notes || '-'}</TableCell>
                      <TableCell className="text-center">
                        <span className={`inline-flex rounded-full px-2 py-1 text-xs font-medium ${getWarehouseStatus(warehouse) === 'active' ? 'bg-primary/10 text-primary' : getWarehouseStatus(warehouse) === 'inventory' ? 'bg-amber-100 text-amber-800' : 'bg-muted text-muted-foreground'}`}>
                          {getWarehouseStatus(warehouse) === 'active'
                            ? (t?.warehouseStatusActive ?? 'نشط')
                            : getWarehouseStatus(warehouse) === 'inventory'
                              ? (t?.warehouseStatusInventory ?? 'تحت الجرد')
                              : (t?.warehouseStatusStopped ?? 'موقوف')}
                        </span>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="inline-flex items-center gap-1">
                          <Button type="button" variant="outline" size="sm" onClick={() => openShelvesDialog(warehouse.id)}>
                            {t?.manageShelvesButton ?? 'إدارة الرفوف'}
                          </Button>
                          <Button type="button" variant="outline" size="icon" onClick={() => router.push(`/admin/data/warehouses/${warehouse.id}/edit`)}>
                            <Pencil className="h-4 w-4" />
                          </Button>
                          <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => startTransition(async () => {
                              const isActive = getWarehouseStatus(warehouse) === 'active';
                              const result = await handleToggleWarehouseActive(warehouse.id, isActive);
                              if (result && 'success' in result && result.success && result.item) {
                                setLocalWarehouses((prev) => prev.map((entry) => entry.id === warehouse.id ? result.item as Warehouse : entry));
                                toast({ title: isActive ? (t?.warehouseDeactivatedSuccess ?? 'تم تعطيل المستودع') : (t?.warehouseActivatedSuccess ?? 'تم تفعيل المستودع') });
                                return;
                              }
                              toast({ title: t?.saveErrorTitle ?? tGlobal?.error ?? 'Error', description: result?.error || 'Failed to update warehouse status', variant: 'destructive' });
                            })}
                          >
                            {getWarehouseStatus(warehouse) === 'active' ? (t?.deactivateLabel ?? 'تعطيل') : (t?.activateLabel ?? 'تفعيل')}
                          </Button>
                          <Button type="button" variant="destructive" size="icon" onClick={() => onDeleteWarehouse(warehouse)}>
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      <Dialog
        open={isShelvesDialogOpen}
        onOpenChange={(open) => {
          setIsShelvesDialogOpen(open);
          if (!open) {
            setEditingShelf(null);
            shelfForm.reset({ name: '', notes: '' });
          }
        }}
      >
        <DialogContent className="w-[96vw] max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{(t?.shelvesDialogTitle ?? 'إدارة رفوف المستودع: {name}').replace('{name}', activeWarehouse?.name || '')}</DialogTitle>
            <DialogDescription>{t?.shelvesDialogDescription ?? 'لكل رف مرجع ثابت ومستقل عن اسم الرف، ويمكنك الإضافة الفردية أو الجماعية.'}</DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="grid gap-3 md:grid-cols-4">
              <div className="rounded-md border p-3">
                <div className="text-xs text-muted-foreground">{t?.warehouseReferenceLabel ?? 'مرجع المستودع'}</div>
                <div className="font-mono text-sm">{activeWarehouse?.warehouseNumber || '-'}</div>
              </div>
              <div className="rounded-md border p-3">
                <div className="text-xs text-muted-foreground">{t?.branchLabel ?? 'الفرع'}</div>
                <div className="text-sm">{activeWarehouse?.branchName || '-'}</div>
              </div>
              <div className="rounded-md border p-3">
                <div className="text-xs text-muted-foreground">{t?.departmentsLabel ?? 'الأقسام التابعة'}</div>
                <div className="text-sm truncate">{Array.isArray(activeWarehouse?.departments) && activeWarehouse.departments.length > 0 ? activeWarehouse.departments.join('، ') : '-'}</div>
              </div>
              <div className="rounded-md border p-3">
                <div className="text-xs text-muted-foreground">{t?.statusLabel ?? 'الحالة'}</div>
                <div className="text-sm">{activeWarehouse ? (getWarehouseStatus(activeWarehouse) === 'active' ? (t?.warehouseStatusActive ?? 'نشط') : getWarehouseStatus(activeWarehouse) === 'inventory' ? (t?.warehouseStatusInventory ?? 'تحت الجرد') : (t?.warehouseStatusStopped ?? 'موقوف')) : '-'}</div>
              </div>
            </div>

            <div className="grid gap-4 lg:grid-cols-2">
              <div className="rounded-lg border p-4 space-y-4">
                <div>
                  <p className="text-sm font-medium">{editingShelf ? (t?.editShelfTitle ?? 'تعديل رف') : (t?.addShelfTitle ?? 'إضافة رف يدوي')}</p>
                  <p className="text-xs text-muted-foreground">{t?.shelfReferenceHint ?? 'يتم إنشاء مرجع فريد وثابت للرف عند الحفظ، ولا يتأثر بتعديل الاسم.'}</p>
                  {activeWarehouse?.inactive ? (
                    <p className="mt-2 text-xs text-amber-600">{t?.inactiveWarehouseShelfHint ?? 'المستودع معطل حالياً، لذلك تم إيقاف إضافة الرفوف الجديدة حتى إعادة تفعيله.'}</p>
                  ) : null}
                </div>
                <Form {...shelfForm}>
                  <form onSubmit={shelfForm.handleSubmit(handleShelfSubmit)} className="space-y-4">
                    {editingShelf && <DocumentLockBanner lockStatus={lockStatus} />}
                    {editingShelf && (
                      <div className="rounded-md border bg-muted/30 px-3 py-2 text-sm">
                        <span className="text-muted-foreground">{t?.shelfReferenceLabel ?? 'مرجع الرف'}: </span>
                        <span className="font-mono">{editingShelf.shelfNumber || '-'}</span>
                      </div>
                    )}
                    <FormField
                      control={shelfForm.control}
                      name="name"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.shelfNameLabel ?? 'اسم الرف'}</FormLabel>
                          <FormControl><Input {...field} placeholder={t?.shelfNamePlaceholder ?? 'مثال: A-01'} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={shelfForm.control}
                      name="notes"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.notesLabel ?? 'ملاحظات'}</FormLabel>
                          <FormControl><Textarea {...field} rows={3} placeholder={t?.shelfNotesPlaceholder ?? 'ملاحظات الرف أو نوع التخزين'} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <div className="flex items-center justify-end gap-2">
                      {editingShelf && (
                        <Button type="button" variant="outline" onClick={() => {
                          setEditingShelf(null);
                          shelfForm.reset({ name: '', notes: '' });
                        }}>
                          {t?.cancelEdit ?? 'إلغاء التعديل'}
                        </Button>
                      )}
                      <Button type="submit" disabled={isPending || isShelfEditLocked || (!!activeWarehouse?.inactive && !editingShelf)}>
                        {editingShelf ? (tGlobal?.save ?? 'حفظ') : (t?.addShelfButton ?? 'إضافة رف')}
                      </Button>
                    </div>
                  </form>
                </Form>
              </div>

              <div className="rounded-lg border p-4 space-y-4">
                <div>
                  <p className="text-sm font-medium">{t?.generateShelvesTitle ?? 'إضافة جماعية للرفوف'}</p>
                  <p className="text-xs text-muted-foreground">{t?.shelfPatternHelp ?? 'النمط: بادئة + فاصل + رقم، مثل A-1 أو R-01.'}</p>
                </div>
                <Form {...generateShelvesForm}>
                  <form onSubmit={generateShelvesForm.handleSubmit(handleGenerateShelvesSubmit)} className="grid gap-3 sm:grid-cols-2">
                    <FormField
                      control={generateShelvesForm.control}
                      name="prefix"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.shelfPrefixLabel ?? 'البادئة'}</FormLabel>
                          <FormControl><Input {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={generateShelvesForm.control}
                      name="separator"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.shelfSeparatorLabel ?? 'الفاصل'}</FormLabel>
                          <FormControl><Input {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={generateShelvesForm.control}
                      name="startNumber"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.shelfStartNumberLabel ?? 'بداية الترقيم'}</FormLabel>
                          <FormControl><Input type="number" {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={generateShelvesForm.control}
                      name="count"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.shelfCountLabel ?? 'عدد الرفوف'}</FormLabel>
                          <FormControl><Input type="number" {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <div className="sm:col-span-2 flex justify-end">
                      <Button type="submit" disabled={isPending || !!activeWarehouse?.inactive}>{t?.generateShelvesButton ?? 'إضافة الرفوف'}</Button>
                    </div>
                  </form>
                </Form>
              </div>
            </div>

            <div className="flex justify-end">
              <Input
                value={shelfSearch}
                onChange={(event) => setShelfSearch(event.target.value)}
                placeholder={t?.shelfSearchPlaceholder ?? 'ابحث بمرجع الرف أو الاسم أو الملاحظات...'}
                className="w-full md:max-w-sm"
              />
            </div>

            <div className="rounded-md border overflow-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{t?.shelfReferenceLabel ?? 'مرجع الرف'}</TableHead>
                    <TableHead>{t?.shelfSequenceLabel ?? 'التسلسل الداخلي'}</TableHead>
                    <TableHead>{t?.shelfNameLabel ?? 'اسم الرف'}</TableHead>
                    <TableHead>{t?.notesLabel ?? 'ملاحظات'}</TableHead>
                    <TableHead className="text-center">{t?.statusLabel ?? 'الحالة'}</TableHead>
                    <TableHead className="text-right">{tGlobal?.actions ?? 'إجراءات'}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredShelves.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={6} className="h-16 text-center text-muted-foreground">
                        {t?.noShelvesFound ?? 'لا توجد رفوف بعد.'}
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredShelves.map((shelf) => (
                      <TableRow key={shelf.id}>
                        <TableCell className="font-mono text-xs">{shelf.shelfNumber || '-'}</TableCell>
                        <TableCell className="font-medium">{shelf.sequence}</TableCell>
                        <TableCell>{shelf.name}</TableCell>
                        <TableCell className="max-w-[260px] truncate">{shelf.notes || '-'}</TableCell>
                        <TableCell className="text-center">
                          <span className={`inline-flex rounded-full px-2 py-1 text-xs font-medium ${shelf.inactive ? 'bg-muted text-muted-foreground' : 'bg-primary/10 text-primary'}`}>
                            {shelf.inactive ? (t?.inactiveLabel ?? 'معطل') : (t?.activeLabel ?? 'نشط')}
                          </span>
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="inline-flex items-center gap-1">
                            <Button type="button" size="icon" variant="outline" onClick={() => onEditShelf(shelf)}>
                              <Pencil className="h-4 w-4" />
                            </Button>
                            <ShelfLabelPrint shelf={shelf} warehouse={activeWarehouse!} t={t} tGlobal={tGlobal} />
                            <Button
                              type="button"
                              variant="outline"
                              size="sm"
                              onClick={() => startTransition(async () => {
                                if (!activeWarehouse) return;
                                const result = await handleToggleShelfActive(activeWarehouse.id, shelf.id, !shelf.inactive);
                                if (result && 'success' in result && result.success && result.item) {
                                  const nextShelf = result.item as Shelf;
                                  setLocalWarehouses((prev) => prev.map((warehouse) => {
                                    if (warehouse.id !== activeWarehouse.id) return warehouse;
                                    return { ...warehouse, shelves: (warehouse.shelves || []).map((entry) => entry.id === nextShelf.id ? nextShelf : entry) };
                                  }));
                                  toast({ title: !shelf.inactive ? (t?.shelfDeactivatedSuccess ?? 'تم تعطيل الرف') : (t?.shelfActivatedSuccess ?? 'تم تفعيل الرف') });
                                  return;
                                }
                                toast({ title: t?.saveErrorTitle ?? tGlobal?.error ?? 'Error', description: result?.error || 'Failed to update shelf status', variant: 'destructive' });
                              })}
                            >
                              {shelf.inactive ? (t?.activateLabel ?? 'تفعيل') : (t?.deactivateLabel ?? 'تعطيل')}
                            </Button>
                            <Button type="button" size="icon" variant="destructive" onClick={() => onDeleteShelf(shelf)}>
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
