"use client";

import { useState, useEffect, useCallback, useMemo } from "react";
import type { MacchinaWithDetails } from "@/src/types/macchina";
import type { ArticoloAssegnatoMacchina } from "@/src/types/artMacchineParti";
import TreeNode from "./TreeNode";
import MacchinaModal from "./MacchinaModal";
import ArticoliMacchinaModal from "./ArticoliMacchinaModal";
import { useStabilimento } from "@/src/contexts/StabilimentoContext";

interface DroppedArticle {
  id: number;
  descrizione: string;
  codice: string;
  barcode?: string | null;
  quantita_residua: number;
  famiglia?: string;
}

interface DropModalState {
  macchinaId: number;
  macchinaNome: string;
  article: DroppedArticle;
}

export default function MacchineTree() {
  const [nodes, setNodes] = useState<MacchinaWithDetails[]>([]);
  const [articlesByMacchina, setArticlesByMacchina] = useState<Record<number, ArticoloAssegnatoMacchina[]>>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const { selectedStabilimento, stabilimenti } = useStabilimento();

  const [copiedNodeId, setCopiedNodeId] = useState<number | null>(null);
  const [isCloning, setIsCloning] = useState(false);

  const [showModal, setShowModal] = useState(false);
  const [editingMacchina, setEditingMacchina] = useState<MacchinaWithDetails | null>(null);
  const [parentInfo, setParentInfo] = useState<{
    parentId: number | null;
    parentStabilimento: number | null;
  }>({ parentId: null, parentStabilimento: null });

  const [deleteConfirm, setDeleteConfirm] = useState<{ 
    id: number; 
    nome: string;
    stabilimentoId: number | null;
    hasArticoli: boolean;
    idMagazzinoRientro: number | null;
  } | null>(null);
  const [deleteMagazzini, setDeleteMagazzini] = useState<{ id: number; descrizione: string }[]>([]);

  const [dropModal, setDropModal] = useState<DropModalState | null>(null);
  const [dropQuantita, setDropQuantita] = useState(1);
  const [dropCausale, setDropCausale] = useState("");
  const [dropSaving, setDropSaving] = useState(false);

  const [showArticlesModal, setShowArticlesModal] = useState<{
    macchinaId: number;
    macchinaNome: string;
    macchinaStabilimentoId: number | null;
    articoli: ArticoloAssegnatoMacchina[];
  } | null>(null);

  const fetchNodes = useCallback(async () => {
    try {
      const res = await fetch("/api/macchine");
      if (!res.ok) throw new Error("Errore nel caricamento");
      const data = await res.json();
      setNodes(data.macchine || []);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Errore sconosciuto");
    }
  }, []);

  const fetchArticoliPerMacchina = useCallback(async () => {
    try {
      const res = await fetch("/api/art-macchine-parti");
      if (!res.ok) return;
      const data = await res.json();
      setArticlesByMacchina(data.articoliPerMacchina || {});
    } catch (err) {
      console.error("Errore caricamento articoli per macchina:", err);
    }
  }, []);

  const loadInitialData = useCallback(async () => {
    setLoading(true);
    setError(null);
    await Promise.all([fetchNodes(), fetchArticoliPerMacchina()]);
    setLoading(false);
  }, [fetchNodes, fetchArticoliPerMacchina]);

  useEffect(() => {
    loadInitialData();
  }, [loadInitialData]);

  useEffect(() => {
    const handleArticoliUpdated = () => {
      fetchArticoliPerMacchina();
    };

    window.addEventListener("articoli-updated", handleArticoliUpdated);
    return () => {
      window.removeEventListener("articoli-updated", handleArticoliUpdated);
    };
  }, [fetchArticoliPerMacchina]);

  const getParentStabilimento = (parentId: number | null): number | null => {
    if (!parentId) return null;
    const parent = nodes.find((n) => n.id === parentId);
    return parent?.id_stabilimento || null;
  };

  const handleAddMachine = () => {
    setEditingMacchina(null);
    setParentInfo({ 
      parentId: null, 
      parentStabilimento: selectedStabilimento?.id || null 
    });
    setShowModal(true);
  };

  const handleAddChild = (parentId: number) => {
    setEditingMacchina(null);
    const parentStabilimento = getParentStabilimento(parentId);
    setParentInfo({ parentId, parentStabilimento });
    setShowModal(true);
  };

  const handleEdit = (node: MacchinaWithDetails) => {
    setEditingMacchina(node);
    setParentInfo({
      parentId: node.id_padre,
      parentStabilimento: getParentStabilimento(node.id_padre),
    });
    setShowModal(true);
  };

  const handleConfirmModal = async (formData: {
    nome: string;
    tipo: string;
    id_stabilimento: string;
    colore_testo: string;
    id_padre?: number | null;
  }) => {
    const payload = {
      nome: formData.nome,
      tipo: formData.tipo,
      id_stabilimento: formData.id_stabilimento ? parseInt(formData.id_stabilimento) : null,
      colore_testo: formData.colore_testo,
      id_padre: formData.id_padre,
    };

    if (editingMacchina) {
      const res = await fetch(`/api/macchine/${editingMacchina.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Errore nell'aggiornamento");
      }
    } else {
      const res = await fetch("/api/macchine", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Errore nella creazione");
      }
    }

    await fetchNodes();
  };

  const handleDelete = async (id: number) => {
    const node = nodes.find((n) => n.id === id);
    if (!node) return;

    // Calcola se questa macchina o i suoi discendenti hanno articoli
    const getDescendantIds = (nodeId: number): number[] => {
      const children = nodes.filter((n) => n.id_padre === nodeId);
      let ids = [nodeId];
      for (const child of children) {
        ids = [...ids, ...getDescendantIds(child.id)];
      }
      return ids;
    };

    const allIds = getDescendantIds(id);
    const hasArticoli = allIds.some((mid) => {
      const arts = articlesByMacchina[mid] || [];
      return arts.some((a) => a.quantita > 0);
    });

    // Se ci sono articoli, carica i magazzini dello stabilimento
    if (hasArticoli && node.id_stabilimento) {
      try {
        const res = await fetch("/api/magazzini");
        if (res.ok) {
          const data = await res.json();
          const filtered = data.magazzini.filter(
            (m: { id: number; descrizione: string; id_stabilimento: number }) => 
              m.id_stabilimento === node.id_stabilimento
          );
          setDeleteMagazzini(filtered);
        }
      } catch (err) {
        console.error("Errore caricamento magazzini:", err);
      }
    }

    setDeleteConfirm({ 
      id, 
      nome: node.nome,
      stabilimentoId: node.id_stabilimento,
      hasArticoli,
      idMagazzinoRientro: null,
    });
  };

  const confirmDelete = async () => {
    if (!deleteConfirm) return;

    // Se ci sono articoli ma non è stato selezionato un magazzino, non procedere
    if (deleteConfirm.hasArticoli && !deleteConfirm.idMagazzinoRientro) {
      return;
    }

    try {
      const res = await fetch(`/api/macchine/${deleteConfirm.id}`, {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          idMagazzinoRientro: deleteConfirm.idMagazzinoRientro,
        }),
      });
      if (!res.ok) throw new Error("Errore nell'eliminazione");
      await Promise.all([fetchNodes(), fetchArticoliPerMacchina()]);
      window.dispatchEvent(new CustomEvent("articoli-updated"));
    } catch (err) {
      console.error("Errore eliminazione:", err);
    } finally {
      setDeleteConfirm(null);
      setDeleteMagazzini([]);
    }
  };

  const handleClone = async (node: MacchinaWithDetails) => {
    setIsCloning(true);
    try {
      const res = await fetch("/api/macchine", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "clone", id: node.id, newParentId: node.id_padre }),
      });
      if (!res.ok) throw new Error("Errore nella clonazione");
      await fetchNodes();
    } catch (err) {
      console.error("Errore clonazione:", err);
    } finally {
      setIsCloning(false);
    }
  };

  const handleCopy = (node: MacchinaWithDetails) => {
    setCopiedNodeId(node.id);
  };

  const handlePaste = async (targetId: number) => {
    if (!copiedNodeId) return;

    setIsCloning(true);
    try {
      const res = await fetch("/api/macchine", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "clone", id: copiedNodeId, newParentId: targetId }),
      });
      if (!res.ok) throw new Error("Errore nell'incolla");
      await fetchNodes();
      setCopiedNodeId(null);
    } catch (err) {
      console.error("Errore incolla:", err);
    } finally {
      setIsCloning(false);
    }
  };

  const handleShowArticles = async (nodeId: number) => {
    const macchina = nodes.find((n) => n.id === nodeId);
    if (!macchina) return;

    // Ricarica sempre i dati freschi dal server prima di mostrare la modale
    try {
      const res = await fetch("/api/art-macchine-parti");
      if (!res.ok) throw new Error("Errore caricamento articoli");
      
      const data = await res.json();
      const freshArticlesByMacchina = data.articoliPerMacchina || {};
      
      // Aggiorna lo state globale
      setArticlesByMacchina(freshArticlesByMacchina);

      const articoliNodo = freshArticlesByMacchina[nodeId] || [];
      
      const getDescendantArticles = (id: number): ArticoloAssegnatoMacchina[] => {
        const children = nodes.filter((n) => n.id_padre === id);
        let result: ArticoloAssegnatoMacchina[] = [];
        for (const child of children) {
          const childArticles = freshArticlesByMacchina[child.id] || [];
          result = [...result, ...childArticles, ...getDescendantArticles(child.id)];
        }
        return result;
      };
      
      const allArticoli = [...articoliNodo, ...getDescendantArticles(nodeId)];
      
      setShowArticlesModal({
        macchinaId: nodeId,
        macchinaNome: macchina.nome,
        macchinaStabilimentoId: macchina.id_stabilimento,
        articoli: allArticoli,
      });
    } catch (err) {
      console.error("Errore caricamento articoli:", err);
    }
  };

  const handleDropArticle = (macchinaId: number, article: unknown) => {
    const droppedArticle = article as DroppedArticle;
    if (!droppedArticle || droppedArticle.quantita_residua <= 0) return;

    const macchina = nodes.find((n) => n.id === macchinaId);
    if (!macchina) return;

    setDropModal({
      macchinaId,
      macchinaNome: macchina.nome,
      article: droppedArticle,
    });
    setDropQuantita(1);
    setDropCausale("");
  };

  const handleConfirmDrop = async () => {
    if (!dropModal) return;

    if (dropQuantita <= 0 || dropQuantita > dropModal.article.quantita_residua) {
      return;
    }

    setDropSaving(true);
    try {
      const res = await fetch("/api/art-macchine-parti/assegna", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          idart: dropModal.article.id,
          idmacchina: dropModal.macchinaId,
          quantita: dropQuantita,
          causale: dropCausale || `Assegnazione a ${dropModal.macchinaNome}`,
        }),
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Errore nell'assegnazione");
      }

      await fetchArticoliPerMacchina();
      setDropModal(null);

      window.dispatchEvent(new CustomEvent("articoli-updated"));
    } catch (err) {
      console.error("Errore assegnazione:", err);
      alert(err instanceof Error ? err.message : "Errore nell'assegnazione");
    } finally {
      setDropSaving(false);
    }
  };

  const filteredNodes = useMemo(() => {
    if (!selectedStabilimento) return [];
    return nodes.filter((n) => n.id_stabilimento === selectedStabilimento.id);
  }, [nodes, selectedStabilimento]);

  const rootNodes = filteredNodes.filter((n) => n.id_padre === null);
  
  const filteredCount = filteredNodes.length;

  // Se non c'è stabilimento selezionato, mostra messaggio
  if (!selectedStabilimento) {
    return (
      <div className="flex flex-col h-full">
        <div className="mb-4">
          <h2 className="text-lg font-semibold text-white">Macchine</h2>
          <p className="text-xs text-zinc-500">Seleziona uno stabilimento per visualizzare le macchine</p>
        </div>
        <div className="flex-1 flex flex-col items-center justify-center text-center p-8 border-2 border-dashed border-zinc-800 rounded-lg">
          <svg className="w-12 h-12 text-zinc-700 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
          </svg>
          <p className="text-zinc-500 text-sm mb-2">Nessuno stabilimento selezionato</p>
          <p className="text-zinc-600 text-xs">
            Seleziona uno stabilimento dal menu in alto per visualizzare e gestire le macchine
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="flex items-center justify-between gap-4 mb-4">
        <div>
          <h2 className="text-lg font-semibold text-white">Macchine</h2>
          <p className="text-xs text-zinc-500">
            {filteredCount} elementi in {selectedStabilimento.descrizione}
          </p>
        </div>
        <button
          onClick={handleAddMachine}
          disabled={isCloning}
          className="p-2 rounded-lg bg-blue-600 text-white hover:bg-blue-500 transition-colors disabled:opacity-50"
          title="Nuova macchina"
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
          </svg>
        </button>
      </div>

      {/* Indicatore clonazione */}
      {isCloning && (
        <div className="mb-3 px-3 py-2 rounded-lg bg-blue-900/30 border border-blue-700/50 flex items-center gap-2">
          <svg className="w-4 h-4 animate-spin text-blue-400" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
          </svg>
          <span className="text-sm text-blue-300">Clonazione in corso...</span>
        </div>
      )}

      {/* Indicatore copia */}
      {copiedNodeId && (
        <div className="mb-3 px-3 py-2 rounded-lg bg-yellow-900/30 border border-yellow-700/50 flex items-center justify-between">
          <span className="text-sm text-yellow-300">
            Nodo copiato. Clicca su "Incolla" per inserirlo.
          </span>
          <button
            onClick={() => setCopiedNodeId(null)}
            className="text-xs text-yellow-400 hover:text-yellow-200"
          >
            Annulla
          </button>
        </div>
      )}

      {/* Contenuto */}
      <div className="flex-1 overflow-y-auto pr-1">
        {loading ? (
          <div className="flex items-center justify-center py-8 text-zinc-500 text-sm">
            <svg className="w-5 h-5 animate-spin mr-2" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
            </svg>
            Caricamento...
          </div>
        ) : error ? (
          <div className="text-center py-8">
            <p className="text-red-400 text-sm mb-2">{error}</p>
            <button onClick={loadInitialData} className="text-xs text-blue-400 hover:underline">
              Riprova
            </button>
          </div>
        ) : rootNodes.length === 0 ? (
          <div className="flex-1 flex flex-col items-center justify-center text-center p-8 border-2 border-dashed border-zinc-800 rounded-lg">
            <svg className="w-12 h-12 text-zinc-700 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
            </svg>
            <p className="text-zinc-500 text-sm mb-2">
              Nessuna macchina in &quot;{selectedStabilimento.descrizione}&quot;
            </p>
            <p className="text-zinc-600 text-xs mb-4">
              Clicca sul pulsante + per aggiungere la prima macchina
            </p>
            <button
              onClick={handleAddMachine}
              className="px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-500 transition-colors"
            >
              Aggiungi macchina
            </button>
          </div>
        ) : (
          <div className="space-y-1">
            {rootNodes.map((node) => (
              <TreeNode
                key={node.id}
                node={node}
                allNodes={filteredNodes}
                level={0}
                articlesByMacchina={articlesByMacchina}
                isCloning={isCloning}
                copiedNodeId={copiedNodeId}
                onAdd={handleAddChild}
                onEdit={handleEdit}
                onDelete={handleDelete}
                onClone={handleClone}
                onCopy={handleCopy}
                onPaste={handlePaste}
                onShowArticles={handleShowArticles}
                onDropArticle={handleDropArticle}
              />
            ))}
          </div>
        )}
      </div>

      {/* Modal */}
      <MacchinaModal
        isOpen={showModal}
        editingMacchina={editingMacchina}
        stabilimenti={stabilimenti}
        parentId={parentInfo.parentId}
        parentStabilimento={parentInfo.parentStabilimento}
        onClose={() => {
          setShowModal(false);
          setEditingMacchina(null);
          setParentInfo({ parentId: null, parentStabilimento: null });
        }}
        onConfirm={handleConfirmModal}
      />

      {/* Delete Confirmation */}
      {deleteConfirm && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={() => { setDeleteConfirm(null); setDeleteMagazzini([]); }} />
          <div className="relative w-full max-w-md bg-zinc-900 rounded-xl border border-zinc-800 shadow-2xl p-5">
            <h3 className="text-lg font-semibold text-white mb-2">Conferma eliminazione</h3>
            <p className="text-sm text-zinc-400 mb-4">
              Sei sicuro di voler eliminare <strong className="text-white">{deleteConfirm.nome}</strong>?
              <br />
              <span className="text-red-400">Verranno eliminati anche tutti i sotto-elementi.</span>
            </p>

            {deleteConfirm.hasArticoli && (
              <div className="mb-4 p-4 rounded-lg bg-yellow-900/20 border border-yellow-700/30">
                <p className="text-sm text-yellow-300 mb-3">
                  Questa macchina contiene articoli assegnati. Seleziona il magazzino dove far rientrare gli articoli:
                </p>
                {deleteMagazzini.length === 0 ? (
                  <p className="text-xs text-red-400">
                    Nessun magazzino disponibile per questo stabilimento. Gli articoli andranno persi.
                  </p>
                ) : (
                  <select
                    value={deleteConfirm.idMagazzinoRientro || ""}
                    onChange={(e) => setDeleteConfirm({
                      ...deleteConfirm,
                      idMagazzinoRientro: e.target.value ? parseInt(e.target.value) : null,
                    })}
                    className="w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-yellow-500"
                  >
                    <option value="">Seleziona magazzino...</option>
                    {deleteMagazzini.map((mag) => (
                      <option key={mag.id} value={mag.id}>
                        {mag.descrizione}
                      </option>
                    ))}
                  </select>
                )}
                {deleteMagazzini.length > 0 && !deleteConfirm.idMagazzinoRientro && (
                  <p className="text-xs text-yellow-400 mt-2">
                    Devi selezionare un magazzino per procedere
                  </p>
                )}
              </div>
            )}

            <div className="flex items-center justify-end gap-3">
              <button
                onClick={() => { setDeleteConfirm(null); setDeleteMagazzini([]); }}
                className="px-4 py-2 text-sm font-medium text-zinc-300 hover:text-white rounded-lg hover:bg-zinc-800 transition-colors"
              >
                Annulla
              </button>
              <button
                onClick={confirmDelete}
                disabled={deleteConfirm.hasArticoli && deleteMagazzini.length > 0 && !deleteConfirm.idMagazzinoRientro}
                className="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Elimina
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Show Articles Modal */}
      {showArticlesModal && (
        <ArticoliMacchinaModal
          macchinaId={showArticlesModal.macchinaId}
          macchinaNome={showArticlesModal.macchinaNome}
          macchinaStabilimentoId={showArticlesModal.macchinaStabilimentoId}
          articoli={showArticlesModal.articoli}
          onClose={() => setShowArticlesModal(null)}
          onArticoloRimosso={async () => {
            await fetchArticoliPerMacchina();
            window.dispatchEvent(new CustomEvent("articoli-updated"));
            // Aggiorna gli articoli nella modale invece di chiuderla
            const macchina = nodes.find((n) => n.id === showArticlesModal.macchinaId);
            if (macchina) {
              // Ricarica gli articoli per questa macchina
              try {
                const res = await fetch("/api/art-macchine-parti");
                if (res.ok) {
                  const data = await res.json();
                  const newArticlesByMacchina = data.articoliPerMacchina || {};
                  
                  const getDescendantArticles = (id: number): ArticoloAssegnatoMacchina[] => {
                    const children = nodes.filter((n) => n.id_padre === id);
                    let result: ArticoloAssegnatoMacchina[] = [];
                    for (const child of children) {
                      const childArticles = newArticlesByMacchina[child.id] || [];
                      result = [...result, ...childArticles, ...getDescendantArticles(child.id)];
                    }
                    return result;
                  };
                  
                  const articoliNodo = newArticlesByMacchina[showArticlesModal.macchinaId] || [];
                  const allArticoli = [...articoliNodo, ...getDescendantArticles(showArticlesModal.macchinaId)];
                  
                  setShowArticlesModal({
                    ...showArticlesModal,
                    articoli: allArticoli,
                  });
                }
              } catch (err) {
                console.error("Errore ricarica articoli:", err);
                setShowArticlesModal(null);
              }
            }
          }}
        />
      )}

      {/* Drop Article Modal */}
      {dropModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={() => setDropModal(null)} />
          <div className="relative w-full max-w-md bg-zinc-900 rounded-xl border border-zinc-800 shadow-2xl">
            <div className="flex items-center justify-between px-5 py-4 border-b border-zinc-800 bg-blue-900/20">
              <div>
                <h3 className="text-lg font-semibold text-white">Assegna Articolo</h3>
                <p className="text-xs text-zinc-500">Trascina e rilascia completato</p>
              </div>
              <button
                onClick={() => setDropModal(null)}
                className="p-1 rounded-lg text-zinc-400 hover:text-white hover:bg-zinc-800"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            <div className="p-5 space-y-4">
              {/* Info articolo */}
              <div className="p-3 rounded-lg bg-zinc-800/50 border border-zinc-700">
                <p className="text-xs text-zinc-500 mb-1">Articolo</p>
                <p className="font-medium text-white">{dropModal.article.descrizione}</p>
                <p className="text-xs text-zinc-500 font-mono">{dropModal.article.codice}</p>
                <p className="text-xs text-zinc-500 mt-1">
                  Disponibili: <span className="text-green-400">{dropModal.article.quantita_residua}</span>
                </p>
              </div>

              {/* Info destinazione */}
              <div className="p-3 rounded-lg bg-blue-900/20 border border-blue-700/50">
                <p className="text-xs text-zinc-500 mb-1">Destinazione</p>
                <p className="font-medium text-blue-300">{dropModal.macchinaNome}</p>
              </div>

              {/* Quantità */}
              <div>
                <label className="block text-sm font-medium text-zinc-400 mb-1">Quantità</label>
                <input
                  type="number"
                  value={dropQuantita}
                  onChange={(e) => setDropQuantita(Math.max(1, Math.min(dropModal.article.quantita_residua, parseInt(e.target.value) || 1)))}
                  min={1}
                  max={dropModal.article.quantita_residua}
                  className="w-full px-4 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white text-lg font-semibold focus:outline-none focus:border-blue-500"
                />
              </div>

              {/* Causale */}
              <div>
                <label className="block text-sm font-medium text-zinc-400 mb-1">Causale (opzionale)</label>
                <input
                  type="text"
                  value={dropCausale}
                  onChange={(e) => setDropCausale(e.target.value)}
                  placeholder="Es: Manutenzione programmata"
                  className="w-full px-4 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-blue-500"
                />
              </div>
            </div>

            <div className="flex items-center justify-end gap-3 px-5 py-4 border-t border-zinc-800">
              <button
                onClick={() => setDropModal(null)}
                className="px-4 py-2 text-sm font-medium text-zinc-300 hover:text-white rounded-lg hover:bg-zinc-800"
              >
                Annulla
              </button>
              <button
                onClick={handleConfirmDrop}
                disabled={dropSaving || dropQuantita <= 0}
                className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-500 disabled:opacity-50 flex items-center gap-2"
              >
                {dropSaving && (
                  <svg className="w-4 h-4 animate-spin" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                  </svg>
                )}
                Assegna
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
