'use client';

import { useMemo, useState, useTransition } from "react";
import { format, parseISO } from "date-fns";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog";
import { useToast } from "@/hooks/use-toast";
import { useDocumentLock } from '@/hooks/use-document-lock';
import { handleDeleteInternalTransfer, handleUpdateInternalTransfer } from "@/lib/actions";
import { DocumentLockBanner } from '@/components/admin/document-lock-banner';
import type { Warehouse } from "@/lib/types";
import { Loader2, Pencil, Trash2 } from "lucide-react";

export type InternalTransferRow = {
  id: string;
  transferNumber?: string;
  date: string | Date;
  materialId: string;
  materialName: string;
  fromWarehouseId: string;
  fromWarehouseName: string;
  fromShelfId: string;
  fromShelfName: string;
  toWarehouseId: string;
  toWarehouseName: string;
  toShelfId: string;
  toShelfName: string;
  quantity: number;
  note?: string;
  createdBy?: string;
};

function formatDate(value: string | Date) {
  if (value instanceof Date) {
    return format(value, "yyyy-MM-dd");
  }
  try {
    return format(parseISO(value), "yyyy-MM-dd");
  } catch {
    return String(value);
  }
}

export default function InternalTransfersTable({
  rows,
  emptyLabel,
  warehouses,
}: {
  rows: InternalTransferRow[];
  emptyLabel: string;
  warehouses: Warehouse[];
}) {
  const [editOpen, setEditOpen] = useState(false);
  const [editRow, setEditRow] = useState<InternalTransferRow | null>(null);
  const [editState, setEditState] = useState({
    fromWarehouseId: "",
    fromShelfId: "",
    toWarehouseId: "",
    toShelfId: "",
    quantity: "",
    date: "",
    note: "",
  });
  const [isUpdating, startUpdateTransition] = useTransition();
  const [isDeleting, startDeleteTransition] = useTransition();
  const { toast } = useToast();
  const { lockStatus } = useDocumentLock('internal-transfer', editRow?.id || '', { enabled: editOpen && !!editRow?.id });
  const isEditLocked = editOpen && !!editRow && lockStatus.isLocked;

  const warehouseById = useMemo(() => new Map(warehouses.map((wh) => [wh.id, wh])), [warehouses]);
  const fromShelves = warehouseById.get(editState.fromWarehouseId)?.shelves || [];
  const toShelves = warehouseById.get(editState.toWarehouseId)?.shelves || [];

  if (rows.length === 0) {
    return <p className="text-sm text-muted-foreground">{emptyLabel}</p>;
  }

  const openEdit = (row: InternalTransferRow) => {
    setEditRow(row);
    setEditState({
      fromWarehouseId: row.fromWarehouseId,
      fromShelfId: row.fromShelfId,
      toWarehouseId: row.toWarehouseId,
      toShelfId: row.toShelfId,
      quantity: String(row.quantity ?? ""),
      date: typeof row.date === "string" ? row.date.slice(0, 10) : formatDate(row.date),
      note: row.note || "",
    });
    setEditOpen(true);
  };

  const closeEdit = () => {
    setEditOpen(false);
    setEditRow(null);
    setEditState({
      fromWarehouseId: "",
      fromShelfId: "",
      toWarehouseId: "",
      toShelfId: "",
      quantity: "",
      date: "",
      note: "",
    });
  };

  const onSubmitEdit = () => {
    if (!editRow) return;
    if (isEditLocked) return;

    const requestedQty = Number(editState.quantity || 0);
    if (!Number.isFinite(requestedQty) || requestedQty <= 0) {
      toast({ title: "خطأ", description: "الكمية غير صحيحة.", variant: "destructive" });
      return;
    }
    if (!editState.fromWarehouseId || !editState.fromShelfId || !editState.toWarehouseId || !editState.toShelfId) {
      toast({ title: "خطأ", description: "يرجى اختيار المواقع بالكامل.", variant: "destructive" });
      return;
    }
    if (editState.fromWarehouseId === editState.toWarehouseId && editState.fromShelfId === editState.toShelfId) {
      toast({ title: "خطأ", description: "لا يمكن اختيار نفس المصدر والوجهة.", variant: "destructive" });
      return;
    }

    startUpdateTransition(async () => {
      const result = await handleUpdateInternalTransfer(editRow.id, {
        materialId: editRow.materialId,
        quantity: requestedQty,
        fromWarehouseId: editState.fromWarehouseId,
        fromShelfId: editState.fromShelfId,
        toWarehouseId: editState.toWarehouseId,
        toShelfId: editState.toShelfId,
        date: editState.date ? new Date(editState.date).toISOString() : undefined,
        note: editState.note || undefined,
      });

      if (result.success) {
        toast({ title: "تم تحديث الارسالية" });
        closeEdit();
      } else {
        toast({ title: "خطأ", description: result.error || "تعذر تحديث الارسالية.", variant: "destructive" });
      }
    });
  };

  const onDelete = (id: string) => {
    startDeleteTransition(async () => {
      const result = await handleDeleteInternalTransfer(id);
      if (result.success) {
        toast({ title: "تم حذف الارسالية" });
      } else {
        toast({ title: "خطأ", description: result.error || "تعذر حذف الارسالية.", variant: "destructive" });
      }
    });
  };

  return (
    <>
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>رقم الارسالية</TableHead>
            <TableHead>التاريخ</TableHead>
            <TableHead>الصنف</TableHead>
            <TableHead>من المستودع</TableHead>
            <TableHead>من الرف</TableHead>
            <TableHead>إلى المستودع</TableHead>
            <TableHead>إلى الرف</TableHead>
            <TableHead className="text-right">الكمية</TableHead>
            <TableHead>ملاحظة</TableHead>
            <TableHead>أضيف بواسطة</TableHead>
            <TableHead className="text-right">الإجراءات</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {rows.map((row) => (
            <TableRow key={row.id}>
              <TableCell className="font-mono">{row.transferNumber || "-"}</TableCell>
              <TableCell className="font-mono">{formatDate(row.date)}</TableCell>
              <TableCell>{row.materialName}</TableCell>
              <TableCell>{row.fromWarehouseName}</TableCell>
              <TableCell>{row.fromShelfName}</TableCell>
              <TableCell>{row.toWarehouseName}</TableCell>
              <TableCell>{row.toShelfName}</TableCell>
              <TableCell className="text-right font-mono">{row.quantity}</TableCell>
              <TableCell>{row.note || "-"}</TableCell>
              <TableCell>{row.createdBy || "-"}</TableCell>
              <TableCell className="text-right">
                <div className="flex justify-end gap-2">
                  <Button type="button" size="icon" variant="ghost" onClick={() => openEdit(row)}>
                    <Pencil className="h-4 w-4" />
                  </Button>
                  <AlertDialog>
                    <AlertDialogTrigger asChild>
                      <Button type="button" size="icon" variant="ghost">
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </AlertDialogTrigger>
                    <AlertDialogContent>
                      <AlertDialogHeader>
                        <AlertDialogTitle>حذف الارسالية</AlertDialogTitle>
                        <AlertDialogDescription>هل أنت متأكد من حذف هذه الارسالية؟ لا يمكن التراجع.</AlertDialogDescription>
                      </AlertDialogHeader>
                      <AlertDialogFooter>
                        <AlertDialogCancel>إلغاء</AlertDialogCancel>
                        <AlertDialogAction onClick={() => onDelete(row.id)}>
                          {isDeleting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                          حذف
                        </AlertDialogAction>
                      </AlertDialogFooter>
                    </AlertDialogContent>
                  </AlertDialog>
                </div>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>

      <Dialog open={editOpen} onOpenChange={(open) => (!open ? closeEdit() : setEditOpen(true))}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>تعديل الارسالية</DialogTitle>
            <DialogDescription>يمكنك تعديل مواقع النقل أو الكمية أو التاريخ.</DialogDescription>
          </DialogHeader>

          <DocumentLockBanner lockStatus={lockStatus} />

          <div className="grid gap-4 sm:grid-cols-2">
            <div className="grid gap-2">
              <span className="text-sm font-medium">من المستودع</span>
              <Select value={editState.fromWarehouseId} onValueChange={(value) => setEditState((prev) => ({ ...prev, fromWarehouseId: value, fromShelfId: "" }))}>
                <SelectTrigger>
                  <SelectValue placeholder="اختر المستودع" />
                </SelectTrigger>
                <SelectContent>
                  {warehouses.map((wh) => (
                    <SelectItem key={wh.id} value={wh.id}>{wh.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <span className="text-sm font-medium">من الرف</span>
              <Select value={editState.fromShelfId} onValueChange={(value) => setEditState((prev) => ({ ...prev, fromShelfId: value }))}>
                <SelectTrigger>
                  <SelectValue placeholder="اختر الرف" />
                </SelectTrigger>
                <SelectContent>
                  {fromShelves.map((shelf) => (
                    <SelectItem key={shelf.id} value={shelf.id}>{shelf.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <span className="text-sm font-medium">إلى المستودع</span>
              <Select value={editState.toWarehouseId} onValueChange={(value) => setEditState((prev) => ({ ...prev, toWarehouseId: value, toShelfId: "" }))}>
                <SelectTrigger>
                  <SelectValue placeholder="اختر المستودع" />
                </SelectTrigger>
                <SelectContent>
                  {warehouses.map((wh) => (
                    <SelectItem key={wh.id} value={wh.id}>{wh.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <span className="text-sm font-medium">إلى الرف</span>
              <Select value={editState.toShelfId} onValueChange={(value) => setEditState((prev) => ({ ...prev, toShelfId: value }))}>
                <SelectTrigger>
                  <SelectValue placeholder="اختر الرف" />
                </SelectTrigger>
                <SelectContent>
                  {toShelves.map((shelf) => (
                    <SelectItem key={shelf.id} value={shelf.id}>{shelf.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <span className="text-sm font-medium">الكمية</span>
              <Input
                type="number"
                min="0"
                step="0.01"
                value={editState.quantity}
                onChange={(event) => setEditState((prev) => ({ ...prev, quantity: event.target.value }))}
              />
            </div>
            <div className="grid gap-2">
              <span className="text-sm font-medium">التاريخ</span>
              <Input
                type="date"
                value={editState.date}
                onChange={(event) => setEditState((prev) => ({ ...prev, date: event.target.value }))}
              />
            </div>
            <div className="grid gap-2 sm:col-span-2">
              <span className="text-sm font-medium">ملاحظة</span>
              <Input
                value={editState.note}
                onChange={(event) => setEditState((prev) => ({ ...prev, note: event.target.value }))}
              />
            </div>
          </div>

          <DialogFooter className="gap-2">
            <Button type="button" variant="outline" onClick={closeEdit}>إلغاء</Button>
            <Button type="button" onClick={onSubmitEdit} disabled={isUpdating || isEditLocked}>
              {isUpdating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              حفظ التعديل
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
