"use client";

import { useState, useEffect } from "react";
import type { MacchinaWithDetails } from "@/src/types/macchina";

interface DestinazioneModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSelect: (macchina: MacchinaWithDetails) => void;
  selectedId?: number | null;
}

function TreeNodeSelectable({
  node,
  allNodes,
  level = 0,
  selectedId,
  onSelect,
}: {
  node: MacchinaWithDetails;
  allNodes: MacchinaWithDetails[];
  level?: number;
  selectedId?: number | null;
  onSelect: (node: MacchinaWithDetails) => void;
}) {
  const [isExpanded, setIsExpanded] = useState(level < 2);
  const children = allNodes.filter((n) => n.id_padre === node.id);
  const isSelected = selectedId === node.id;

  const getNodeTypeIcon = () => {
    switch (node.tipo) {
      case "macchina": return "🔧";
      case "gruppo": return "📁";
      case "parte": return "⚙️";
      default: return "📄";
    }
  };

  const getNodeTypeBg = () => {
    if (isSelected) return "bg-blue-600 border-blue-500";
    switch (node.tipo) {
      case "macchina": return "bg-blue-900/30 border-blue-700/50 hover:bg-blue-800/40";
      case "gruppo": return "bg-purple-900/30 border-purple-700/50 hover:bg-purple-800/40";
      case "parte": return "bg-zinc-800/50 border-zinc-700/50 hover:bg-zinc-700/50";
      default: return "bg-zinc-800 border-zinc-700 hover:bg-zinc-700";
    }
  };

  return (
    <div style={{ marginLeft: `${level * 16}px` }} className="mb-1">
      <div
        className={`flex items-center gap-2 px-3 py-2 rounded-lg border cursor-pointer transition-all ${getNodeTypeBg()}`}
        onClick={() => onSelect(node)}
      >
        {children.length > 0 && (
          <button
            onClick={(e) => {
              e.stopPropagation();
              setIsExpanded(!isExpanded);
            }}
            className="w-5 h-5 flex items-center justify-center text-zinc-400 hover:text-white"
          >
            <svg
              className={`w-4 h-4 transition-transform ${isExpanded ? "rotate-90" : ""}`}
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
          </button>
        )}
        {children.length === 0 && <div className="w-5" />}

        <span className="text-sm">{getNodeTypeIcon()}</span>
        <span className={`flex-1 text-sm font-medium truncate ${isSelected ? "text-white" : "text-zinc-200"}`}>
          {node.nome}
        </span>

        {isSelected && (
          <svg className="w-5 h-5 text-white" fill="currentColor" viewBox="0 0 20 20">
            <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
          </svg>
        )}
      </div>

      {isExpanded && children.length > 0 && (
        <div className="mt-1">
          {children.map((child) => (
            <TreeNodeSelectable
              key={child.id}
              node={child}
              allNodes={allNodes}
              level={level + 1}
              selectedId={selectedId}
              onSelect={onSelect}
            />
          ))}
        </div>
      )}
    </div>
  );
}

export default function DestinazioneModal({
  isOpen,
  onClose,
  onSelect,
  selectedId,
}: DestinazioneModalProps) {
  const [nodes, setNodes] = useState<MacchinaWithDetails[]>([]);
  const [loading, setLoading] = useState(false);
  const [localSelectedId, setLocalSelectedId] = useState<number | null>(selectedId || null);
  const [localSelectedNode, setLocalSelectedNode] = useState<MacchinaWithDetails | null>(null);

  useEffect(() => {
    if (isOpen) {
      setLoading(true);
      setLocalSelectedId(selectedId || null);
      
      fetch("/api/macchine")
        .then((res) => res.json())
        .then((data) => {
          setNodes(data.macchine || []);
          if (selectedId) {
            const found = data.macchine?.find((n: MacchinaWithDetails) => n.id === selectedId);
            setLocalSelectedNode(found || null);
          }
        })
        .catch((error) => {
          console.error("Errore caricamento macchine:", error);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [isOpen, selectedId]);

  const handleNodeSelect = (node: MacchinaWithDetails) => {
    setLocalSelectedId(node.id);
    setLocalSelectedNode(node);
  };

  const handleConfirm = () => {
    if (localSelectedNode) {
      onSelect(localSelectedNode);
      onClose();
    }
  };

  if (!isOpen) return null;

  const rootNodes = nodes.filter((n) => n.id_padre === null);

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center">
      <div className="absolute inset-0 bg-black/70 backdrop-blur-sm" onClick={onClose} />
      
      <div className="relative w-full max-w-lg max-h-[80vh] bg-zinc-900 rounded-xl border border-zinc-800 shadow-2xl flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b border-zinc-800">
          <div>
            <h3 className="text-lg font-semibold text-white">Seleziona Destinazione</h3>
            <p className="text-xs text-zinc-500">Scegli la macchina o parte a cui assegnare l'articolo</p>
          </div>
          <button
            onClick={onClose}
            className="p-1 rounded-lg text-zinc-400 hover:text-white hover:bg-zinc-800 transition-colors"
          >
            <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>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-4">
          {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>
          ) : rootNodes.length === 0 ? (
            <div className="text-center py-8">
              <svg className="w-12 h-12 text-zinc-700 mx-auto 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">Nessuna macchina disponibile</p>
              <p className="text-zinc-600 text-xs mt-1">Aggiungi prima delle macchine nel sistema</p>
            </div>
          ) : (
            <div className="space-y-1">
              {rootNodes.map((node) => (
                <TreeNodeSelectable
                  key={node.id}
                  node={node}
                  allNodes={nodes}
                  level={0}
                  selectedId={localSelectedId}
                  onSelect={handleNodeSelect}
                />
              ))}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between px-5 py-4 border-t border-zinc-800 bg-zinc-900/50">
          {localSelectedNode ? (
            <div className="flex items-center gap-2 text-sm">
              <span className="text-zinc-500">Selezionato:</span>
              <span className="text-blue-400 font-medium">{localSelectedNode.nome}</span>
            </div>
          ) : (
            <div className="text-sm text-zinc-500">Nessuna selezione</div>
          )}
          
          <div className="flex items-center gap-3">
            <button
              onClick={onClose}
              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={handleConfirm}
              disabled={!localSelectedNode}
              className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Conferma
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
