import React, { useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ArrowRight, Loader2, Package, Trash2, History, Filter, Eye, PackageCheck, FileText } from "lucide-react";
import { toast } from "sonner";
import { API } from "@/apis/configs/axiosConfigs";
import { WarehouseAPI } from "@/apis/WarehouseAPI";

const AUTH_RUT_STORAGE_KEY = "auth_rut";

const unwrap = (response) => {
  const payload = response?.data;
  if (payload && typeof payload === "object" && "data" in payload) {
    const nested = payload.data;
    if (nested && typeof nested === "object" && "detail" in nested) {
      return nested.detail;
    }
    return nested;
  }
  return payload;
};

const readRutFromStorage = () => {
  if (typeof window === "undefined") return null;
  return window.localStorage.getItem(AUTH_RUT_STORAGE_KEY);
};


const getCompanyId = async () => {
  const rut = readRutFromStorage();
  if (!rut) return null;
  const meResponse = await API.post("/auth/me", { rut });
  return meResponse?.data?.data?.detail?.idcompany ?? null;
};

export default function InternalTransfers() {
  const queryClient = useQueryClient();
  const [companyId, setCompanyId] = useState(null);
  const [fromWarehouseId, setFromWarehouseId] = useState("");
  const [toWarehouseId, setToWarehouseId] = useState("");
  const [lines, setLines] = useState([]);
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [notes, setNotes] = useState("");

  const [searchProduct, setSearchProduct] = useState("");
  const [addProductId, setAddProductId] = useState("");
  const [addQty, setAddQty] = useState("1");

  React.useEffect(() => {
    let mounted = true;
    getCompanyId().then((id) => {
      if (mounted && id) setCompanyId(String(id));
    });
    return () => { mounted = false; };
  }, []);

  const { data: warehouses = [] } = useQuery({
    queryKey: ["warehouses", companyId],
    queryFn: () => WarehouseAPI.getByCompanyId(companyId),
    enabled: Boolean(companyId),
  });

  const { data: products = [] } = useQuery({
    queryKey: ["products-transfer", companyId],
    queryFn: async () => {
      const res = await API.get("/products", { params: { idcompany: companyId } });
      return unwrap(res) ?? [];
    },
    enabled: Boolean(companyId),
  });

  const { data: stockData = [] } = useQuery({
    queryKey: ["inventory-stock-transfer", companyId, fromWarehouseId],
    queryFn: async () => {
      const res = await API.get("/inventory-stocks", {
        params: { idcompany: companyId, idwarehouse: fromWarehouseId },
      });
      return unwrap(res) ?? [];
    },
    enabled: Boolean(companyId && fromWarehouseId),
  });

  const stockByProduct = useMemo(() => {
    const map = {};
    (stockData || []).forEach((row) => {
      const pid = String(row.idproduct);
      map[pid] = (map[pid] || 0) + Number(row.quantity || 0);
    });
    return map;
  }, [stockData]);

  const filteredProducts = useMemo(() => {
    const withStock = products.filter((p) => (stockByProduct[String(p.id)] || 0) > 0);
    if (!searchProduct.trim()) return withStock;
    const term = searchProduct.toLowerCase();
    return withStock.filter(
      (p) =>
        (p.name || "").toLowerCase().includes(term) ||
        (p.sku || "").toLowerCase().includes(term)
    );
  }, [products, searchProduct, stockByProduct]);

  const transferMutation = useMutation({
    mutationFn: async (payload) => {
      const res = await API.post("/internal-transfers/generic", payload);
      return unwrap(res);
    },
    onSuccess: () => {
      toast.success("Transferencia aplicada: descontada en origen y acreditada en destino.");
      setLines([]);
      setNotes("");
      setConfirmOpen(false);
      queryClient.invalidateQueries({ queryKey: ["inventory-stock-transfer"] });
    },
    onError: (err) => {
      toast.error(err?.response?.data?.data?.message || err.message || "Error al transferir.");
    },
  });

  const handleAddLine = () => {
    if (!addProductId || !addQty || Number(addQty) <= 0) return;
    const existing = lines.find((l) => String(l.idproduct) === String(addProductId));
    if (existing) {
      setLines(
        lines.map((l) =>
          String(l.idproduct) === String(addProductId)
            ? { ...l, quantity: l.quantity + Number(addQty) }
            : l
        )
      );
    } else {
      const prod = products.find((p) => String(p.id) === String(addProductId));
      setLines([
        ...lines,
        {
          idproduct: Number(addProductId),
          quantity: Number(addQty),
          name: prod?.name || "",
          sku: prod?.sku || "",
        },
      ]);
    }
    setAddProductId("");
    setAddQty("1");
  };

  const handleRemoveLine = (idproduct) => {
    setLines(lines.filter((l) => l.idproduct !== idproduct));
  };

  const handleSubmit = () => {
    if (!fromWarehouseId || !toWarehouseId || lines.length === 0) {
      toast.error("Selecciona bodegas y agrega productos.");
      return;
    }
    setConfirmOpen(true);
  };

  const handleConfirm = () => {
    transferMutation.mutate({
      idcompany: Number(companyId),
      from_warehouse_id: Number(fromWarehouseId),
      to_warehouse_id: Number(toWarehouseId),
      items: lines.map((l) => ({ idproduct: l.idproduct, quantity: l.quantity })),
      notes: notes || null,
    });
  };

  const fromWarehouse = warehouses.find((w) => String(w.id) === fromWarehouseId);
  const toWarehouse = warehouses.find((w) => String(w.id) === toWarehouseId);

  const warehouseTypeLabel = {
    raw_material: "Materia prima",
    finished_goods: "Producto terminado",
    picking_sales: "Picking (ventas)",
    dispatch: "Despachos",
    buffer: "Pulmón (intermedio)",
  };

  // -------- HISTORIAL --------
  const [tab, setTab] = useState("new");
  const [historyFilters, setHistoryFilters] = useState({
    status: "all", from_warehouse_id: "", to_warehouse_id: "", date_from: "", date_to: "", search: "",
  });
  const [historyDetailId, setHistoryDetailId] = useState(null);

  const historyQuery = useQuery({
    queryKey: ["internal-transfers-history", companyId, historyFilters],
    queryFn: async () => {
      const params = { idcompany: companyId, perPage: 50 };
      Object.entries(historyFilters).forEach(([k, v]) => { if (v && v !== "all") params[k] = v; });
      const res = await API.get("/internal-transfers", { params });
      return unwrap(res);
    },
    enabled: Boolean(companyId && tab === "history"),
  });

  const historyDetailQuery = useQuery({
    queryKey: ["internal-transfer-detail", historyDetailId],
    queryFn: async () => {
      const res = await API.get(`/internal-transfers/${historyDetailId}`);
      return unwrap(res);
    },
    enabled: Boolean(historyDetailId),
  });

  const receiveMutation = useMutation({
    mutationFn: async () => {
      const res = await API.post(`/internal-transfers/${historyDetailId}/receive`, {});
      return unwrap(res);
    },
    onSuccess: () => {
      toast.success("Recepción confirmada");
      queryClient.invalidateQueries({ queryKey: ["internal-transfers-history"] });
      queryClient.invalidateQueries({ queryKey: ["internal-transfer-detail", historyDetailId] });
    },
    onError: (err) => toast.error(err?.response?.data?.data?.message || err.message || "Error al recibir"),
  });

  const cancelTransferMutation = useMutation({
    mutationFn: async () => {
      const res = await API.post(`/internal-transfers/${historyDetailId}/cancel`);
      return unwrap(res);
    },
    onSuccess: () => {
      toast.success("Transferencia cancelada y stock devuelto a origen");
      queryClient.invalidateQueries({ queryKey: ["internal-transfers-history"] });
      queryClient.invalidateQueries({ queryKey: ["internal-transfer-detail", historyDetailId] });
    },
    onError: (err) => toast.error(err?.response?.data?.data?.message || err.message || "Error al cancelar"),
  });

  const dispatchGuideMutation = useMutation({
    mutationFn: async () => {
      const res = await API.post(`/internal-transfers/${historyDetailId}/dispatch-guide`);
      return unwrap(res);
    },
    onSuccess: (data) => {
      toast.success(`Guía DTE 52 emitida: folio ${data?.folio || ""}`);
      queryClient.invalidateQueries({ queryKey: ["internal-transfer-detail", historyDetailId] });
    },
    onError: (err) => toast.error(err?.response?.data?.data?.message || err.message || "Error al emitir guía"),
  });

  const STATUS_LABELS_TRANSFER = {
    draft: "Borrador", in_transit: "En tránsito", received: "Recibida",
    completed: "Completada", cancelled: "Cancelada",
  };

  const STATUS_COLORS_TRANSFER = {
    draft: "bg-gray-200 text-gray-700",
    in_transit: "bg-amber-100 text-amber-800",
    received: "bg-blue-100 text-blue-800",
    completed: "bg-green-100 text-green-800",
    cancelled: "bg-red-100 text-red-700",
  };

  if (!companyId) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="animate-spin mr-2" /> Cargando empresa...
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-blue-50 p-6">
      <div className="max-w-7xl mx-auto space-y-6">
        <div className="flex items-center gap-3">
          <Package className="w-8 h-8 text-blue-600" />
          <div>
            <h1 className="text-3xl font-bold text-gray-900">Transferencias entre Bodegas</h1>
            <p className="text-gray-500 text-sm">Gestiona movimientos internos con trazabilidad completa</p>
          </div>
        </div>

      <Tabs value={tab} onValueChange={setTab} className="w-full">
        <TabsList className="grid w-full max-w-md grid-cols-2 bg-white border shadow-sm">
          <TabsTrigger value="new"><Package className="w-4 h-4 mr-1" /> Nueva transferencia</TabsTrigger>
          <TabsTrigger value="history"><History className="w-4 h-4 mr-1" /> Historial</TabsTrigger>
        </TabsList>

        <TabsContent value="new" className="space-y-6 mt-4">
      <Card className="shadow-sm border-white/40">
        <CardHeader className="border-b bg-white/70">
          <CardTitle className="flex items-center gap-2">
            <Package className="h-5 w-5" />
            Transferencias entre Bodegas
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-end">
            <div className="space-y-2">
              <Label>Bodega Origen</Label>
              <Select value={fromWarehouseId} onValueChange={setFromWarehouseId}>
                <SelectTrigger>
                  <SelectValue placeholder="Seleccionar origen..." />
                </SelectTrigger>
                <SelectContent>
                  {warehouses
                    .filter((w) => String(w.id) !== toWarehouseId)
                    .map((w) => (
                      <SelectItem key={w.id} value={String(w.id)}>
                        {w.name}{" "}
                        <span className="text-muted-foreground text-xs">
                          ({warehouseTypeLabel[w.warehouse_type] || w.warehouse_type || "Sin tipo"})
                        </span>
                      </SelectItem>
                    ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>Bodega Destino</Label>
              <Select value={toWarehouseId} onValueChange={setToWarehouseId}>
                <SelectTrigger>
                  <SelectValue placeholder="Seleccionar destino..." />
                </SelectTrigger>
                <SelectContent>
                  {warehouses
                    .filter((w) => String(w.id) !== fromWarehouseId)
                    .map((w) => (
                      <SelectItem key={w.id} value={String(w.id)}>
                        {w.name}{" "}
                        <span className="text-muted-foreground text-xs">
                          ({warehouseTypeLabel[w.warehouse_type] || w.warehouse_type || "Sin tipo"})
                        </span>
                      </SelectItem>
                    ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          {fromWarehouseId && toWarehouseId && (
            <div className="flex items-center gap-2 text-sm bg-muted p-3 rounded-md">
              <Badge variant="outline">{fromWarehouse?.name}</Badge>
              <ArrowRight className="h-4 w-4" />
              <Badge variant="outline">{toWarehouse?.name}</Badge>
            </div>
          )}
        </CardContent>
      </Card>

      {fromWarehouseId && toWarehouseId && (
        <Card className="shadow-sm border-white/40">
          <CardHeader className="border-b bg-white/70">
            <CardTitle className="text-base">Agregar Productos</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <Input
              placeholder="Buscar producto por nombre o SKU..."
              value={searchProduct}
              onChange={(e) => setSearchProduct(e.target.value)}
            />

            <div className="grid grid-cols-1 md:grid-cols-[1fr_120px_auto] gap-2 items-end">
              <div className="space-y-1">
                <Label>Producto</Label>
                <Select value={addProductId} onValueChange={setAddProductId}>
                  <SelectTrigger>
                    <SelectValue placeholder="Seleccionar producto..." />
                  </SelectTrigger>
                  <SelectContent>
                    <ScrollArea className="max-h-60">
                      {filteredProducts.map((p) => (
                        <SelectItem key={p.id} value={String(p.id)}>
                          {p.sku} – {p.name}
                          {fromWarehouseId && (
                            <span className="text-muted-foreground ml-1">
                              (stock: {stockByProduct[String(p.id)] ?? 0})
                            </span>
                          )}
                        </SelectItem>
                      ))}
                    </ScrollArea>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1">
                <Label>Cantidad</Label>
                <Input
                  type="number"
                  min="1"
                  value={addQty}
                  onChange={(e) => setAddQty(e.target.value)}
                />
              </div>
              <Button onClick={handleAddLine} disabled={!addProductId}>
                Agregar
              </Button>
            </div>

            {lines.length > 0 && (
              <div className="border rounded-md bg-white overflow-auto">
                <table className="w-full text-sm">
                  <thead className="bg-gray-50">
                    <tr className="border-b">
                      <th className="text-left p-2">SKU</th>
                      <th className="text-left p-2">Producto</th>
                      <th className="text-right p-2">Cantidad</th>
                      <th className="text-right p-2">Stock Origen</th>
                      <th className="p-2"></th>
                    </tr>
                  </thead>
                  <tbody>
                    {lines.map((line) => (
                      <tr key={line.idproduct} className="border-b">
                        <td className="p-2 font-mono">{line.sku}</td>
                        <td className="p-2">{line.name}</td>
                        <td className="p-2 text-right">{line.quantity}</td>
                        <td className="p-2 text-right">
                          <span
                            className={
                              (stockByProduct[String(line.idproduct)] ?? 0) < line.quantity
                                ? "text-red-600 font-medium"
                                : "text-green-600"
                            }
                          >
                            {stockByProduct[String(line.idproduct)] ?? 0}
                          </span>
                        </td>
                        <td className="p-2 text-right">
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => handleRemoveLine(line.idproduct)}
                          >
                            <Trash2 className="h-4 w-4 text-destructive" />
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}

            <div className="space-y-2">
              <Label>Notas (opcional)</Label>
              <Input
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="Observaciones de la transferencia..."
              />
            </div>

            <Button
              className="w-full"
              onClick={handleSubmit}
              disabled={lines.length === 0}
            >
              Confirmar Transferencia ({lines.length} producto{lines.length !== 1 ? "s" : ""})
            </Button>
          </CardContent>
        </Card>
      )}

      <Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Confirmar Transferencia</DialogTitle>
          </DialogHeader>
          <div className="space-y-3 text-sm">
            <p>
              <strong>Origen:</strong> {fromWarehouse?.name}
            </p>
            <p>
              <strong>Destino:</strong> {toWarehouse?.name}
            </p>
            <p>
              <strong>Productos:</strong> {lines.length}
            </p>
            <p>
              <strong>Unidades totales:</strong>{" "}
              {lines.reduce((sum, l) => sum + l.quantity, 0)}
            </p>
            {notes && (
              <p>
                <strong>Notas:</strong> {notes}
              </p>
            )}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setConfirmOpen(false)}>
              Cancelar
            </Button>
            <Button onClick={handleConfirm} disabled={transferMutation.isPending}>
              {transferMutation.isPending && <Loader2 className="animate-spin mr-2 h-4 w-4" />}
              Ejecutar Transferencia
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
        </TabsContent>

        <TabsContent value="history" className="mt-4 space-y-3">
          <Card className="shadow-sm border-white/40">
            <CardHeader className="border-b bg-white/70">
              <CardTitle className="flex items-center gap-2"><Filter className="w-5 h-5" /> Filtros</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-2">
                <div>
                  <Label>Estado</Label>
                  <Select value={historyFilters.status} onValueChange={(v) => setHistoryFilters((p) => ({ ...p, status: v }))}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">Todos</SelectItem>
                      <SelectItem value="in_transit">En tránsito</SelectItem>
                      <SelectItem value="received">Recibida</SelectItem>
                      <SelectItem value="cancelled">Cancelada</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>Origen</Label>
                  <Select value={historyFilters.from_warehouse_id} onValueChange={(v) => setHistoryFilters((p) => ({ ...p, from_warehouse_id: v === "all" ? "" : v }))}>
                    <SelectTrigger><SelectValue placeholder="Cualquiera" /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">Cualquiera</SelectItem>
                      {warehouses.map((w) => (<SelectItem key={String(w.id)} value={String(w.id)}>{w.name}</SelectItem>))}
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>Destino</Label>
                  <Select value={historyFilters.to_warehouse_id} onValueChange={(v) => setHistoryFilters((p) => ({ ...p, to_warehouse_id: v === "all" ? "" : v }))}>
                    <SelectTrigger><SelectValue placeholder="Cualquiera" /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">Cualquiera</SelectItem>
                      {warehouses.map((w) => (<SelectItem key={String(w.id)} value={String(w.id)}>{w.name}</SelectItem>))}
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>Desde</Label>
                  <Input type="date" value={historyFilters.date_from} onChange={(e) => setHistoryFilters((p) => ({ ...p, date_from: e.target.value }))} />
                </div>
                <div>
                  <Label>Hasta</Label>
                  <Input type="date" value={historyFilters.date_to} onChange={(e) => setHistoryFilters((p) => ({ ...p, date_to: e.target.value }))} />
                </div>
                <div>
                  <Label>Buscar</Label>
                  <Input placeholder="N° o nota" value={historyFilters.search} onChange={(e) => setHistoryFilters((p) => ({ ...p, search: e.target.value }))} />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="shadow-sm border-white/40">
            <CardHeader className="border-b bg-white/70">
              <CardTitle>Transferencias</CardTitle>
            </CardHeader>
            <CardContent>
              {historyQuery.isLoading ? (
                <div className="flex items-center gap-2"><Loader2 className="h-4 w-4 animate-spin" /> Cargando…</div>
              ) : !(historyQuery.data?.detail || historyQuery.data || []).length ? (
                <p className="text-sm text-gray-500">Sin transferencias para los filtros aplicados.</p>
              ) : (
                <div className="overflow-auto rounded-md border bg-white">
                <table className="w-full text-sm">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="text-left p-2">N°</th>
                      <th className="text-left p-2">Origen</th>
                      <th className="text-left p-2">Destino</th>
                      <th className="text-right p-2">Ítems</th>
                      <th className="text-left p-2">Estado</th>
                      <th className="text-left p-2">SR origen</th>
                      <th className="text-left p-2">Fecha</th>
                      <th className="text-left p-2">Usuario</th>
                      <th className="p-2"></th>
                    </tr>
                  </thead>
                  <tbody>
                    {(historyQuery.data?.detail || historyQuery.data || []).map((tr) => (
                      <tr key={tr.id} className="border-t hover:bg-gray-50">
                        <td className="p-2 font-mono">{tr.transfer_number}</td>
                        <td className="p-2">{tr.from_warehouse?.name || "—"}</td>
                        <td className="p-2">{tr.to_warehouse?.name || "—"}</td>
                        <td className="p-2 text-right">{(tr.items || []).length}</td>
                        <td className="p-2">
                          <Badge className={STATUS_COLORS_TRANSFER[tr.status] || ""}>
                            {STATUS_LABELS_TRANSFER[tr.status] || tr.status}
                          </Badge>
                        </td>
                        <td className="p-2 text-xs font-mono">
                          {tr.supply_request?.request_number || "—"}
                        </td>
                        <td className="p-2 text-xs text-gray-500">{tr.created_at?.substring(0, 16).replace("T", " ")}</td>
                        <td className="p-2 text-xs">{tr.user?.user_name || tr.user?.email || "—"}</td>
                        <td className="p-2 text-right">
                          <Button size="sm" variant="outline" onClick={() => setHistoryDetailId(tr.id)}>
                            <Eye className="w-4 h-4" />
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Dialog detalle historial */}
      <Dialog open={Boolean(historyDetailId)} onOpenChange={(v) => { if (!v) setHistoryDetailId(null); }}>
        <DialogContent className="max-w-3xl max-h-[85vh] flex flex-col">
          <DialogHeader>
            <DialogTitle>Detalle Transferencia {historyDetailQuery.data?.transfer_number || ""}</DialogTitle>
          </DialogHeader>
          <ScrollArea className="flex-1 pr-3">
            {historyDetailQuery.isLoading ? (
              <p className="text-sm text-gray-500">Cargando…</p>
            ) : historyDetailQuery.data ? (
              <div className="space-y-3">
                <div className="grid grid-cols-2 gap-2 text-sm">
                  <div><strong>Origen:</strong> {historyDetailQuery.data.from_warehouse?.name} {historyDetailQuery.data.from_warehouse?.rut_for_dte ? <span className="text-xs text-gray-500">({historyDetailQuery.data.from_warehouse.rut_for_dte})</span> : null}</div>
                  <div><strong>Destino:</strong> {historyDetailQuery.data.to_warehouse?.name} {historyDetailQuery.data.to_warehouse?.rut_for_dte ? <span className="text-xs text-gray-500">({historyDetailQuery.data.to_warehouse.rut_for_dte})</span> : null}</div>
                  <div><strong>Estado:</strong> <Badge className={STATUS_COLORS_TRANSFER[historyDetailQuery.data.status] || ""}>{STATUS_LABELS_TRANSFER[historyDetailQuery.data.status] || historyDetailQuery.data.status}</Badge></div>
                  <div><strong>Fecha:</strong> {historyDetailQuery.data.created_at?.substring(0, 19).replace("T", " ")}</div>
                  <div><strong>Usuario:</strong> {historyDetailQuery.data.user?.user_name || historyDetailQuery.data.user?.email || "—"}</div>
                  <div><strong>Recibido por:</strong> {historyDetailQuery.data.receiver?.user_name || historyDetailQuery.data.receiver?.email || "—"}</div>
                  {historyDetailQuery.data.supply_request?.request_number ? (
                    <div className="col-span-2">
                      <strong>Solicitud abastecimiento:</strong>{" "}
                      {historyDetailQuery.data.supply_request.request_number}
                      {historyDetailQuery.data.supply_request.status ? ` (${historyDetailQuery.data.supply_request.status})` : ""}
                    </div>
                  ) : null}
                </div>
                {(() => {
                  const docs = historyDetailQuery.data.tax_documents || [];
                  const emitted = docs.find((d) => d.status === "emitted");
                  if (emitted) {
                    return (
                      <div className="bg-blue-50 border border-blue-200 p-2 rounded text-xs flex items-center justify-between">
                        <div>
                          <strong>Guía DTE 52:</strong> Folio {emitted.folio} ({emitted.emitted_at?.substring(0, 10)})
                        </div>
                        {emitted.pdf_url ? (
                          <a href={emitted.pdf_url} target="_blank" rel="noreferrer" className="text-blue-600 underline">Ver PDF</a>
                        ) : null}
                      </div>
                    );
                  }
                  const failed = docs.find((d) => d.status === "failed");
                  if (failed) {
                    return (
                      <div className="bg-red-50 border border-red-200 p-2 rounded text-xs">
                        <strong>Último intento DTE 52 falló:</strong> {failed.error_message || "Error desconocido"}
                      </div>
                    );
                  }
                  return null;
                })()}
                {historyDetailQuery.data.notes ? (
                  <div className="bg-gray-50 p-2 rounded text-xs"><strong>Notas:</strong> {historyDetailQuery.data.notes}</div>
                ) : null}

                <table className="w-full text-sm">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="text-left p-2">SKU</th>
                      <th className="text-left p-2">Producto</th>
                      <th className="text-right p-2">Cantidad</th>
                      <th className="text-right p-2">Recibida</th>
                      <th className="text-right p-2">Costo unit.</th>
                      <th className="text-right p-2">Lote</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(historyDetailQuery.data.items || []).map((it) => (
                      <tr key={it.id} className="border-t">
                        <td className="p-2 font-mono">{it.product?.sku}</td>
                        <td className="p-2">{it.product?.name}</td>
                        <td className="p-2 text-right">{Number(it.quantity).toLocaleString("es-CL")}</td>
                        <td className="p-2 text-right">{it.quantity_received != null ? Number(it.quantity_received).toLocaleString("es-CL") : "—"}</td>
                        <td className="p-2 text-right">{it.unit_cost != null ? Number(it.unit_cost).toLocaleString("es-CL", { style: "currency", currency: "CLP" }) : "—"}</td>
                        <td className="p-2 text-right">{it.idlot ?? "—"}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : null}
          </ScrollArea>
          <DialogFooter>
            {historyDetailQuery.data && historyDetailQuery.data.status === "in_transit" ? (
              <Button onClick={() => receiveMutation.mutate()} disabled={receiveMutation.isPending} variant="secondary">
                {receiveMutation.isPending ? <Loader2 className="w-4 h-4 animate-spin mr-1" /> : <PackageCheck className="w-4 h-4 mr-1" />}
                Marcar como recibida
              </Button>
            ) : null}
            {historyDetailQuery.data && historyDetailQuery.data.status === "in_transit" ? (
              <Button
                onClick={() => {
                  if (confirm("¿Confirmas que deseas cancelar esta transferencia? El stock será devuelto a la bodega origen.")) {
                    cancelTransferMutation.mutate();
                  }
                }}
                disabled={cancelTransferMutation.isPending}
                variant="destructive"
              >
                {cancelTransferMutation.isPending ? <Loader2 className="w-4 h-4 animate-spin mr-1" /> : null}
                Cancelar transferencia
              </Button>
            ) : null}
            {(() => {
              const t = historyDetailQuery.data;
              if (!t) return null;
              const alreadyEmitted = (t.tax_documents || []).some((d) => d.status === "emitted");
              if (alreadyEmitted) return null;
              return (
                <Button
                  onClick={() => dispatchGuideMutation.mutate()}
                  disabled={dispatchGuideMutation.isPending}
                  variant="outline"
                >
                  {dispatchGuideMutation.isPending ? <Loader2 className="w-4 h-4 animate-spin mr-1" /> : <FileText className="w-4 h-4 mr-1" />}
                  Emitir Guía DTE 52
                </Button>
              );
            })()}
            <Button variant="outline" onClick={() => setHistoryDetailId(null)}>Cerrar</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      </div>
    </div>
  );
}
