"use client";

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

function toRgb(color: string | null | undefined): { r: number; g: number; b: number } | null {
  if (!color || typeof color !== "string") return null;
  const c = color.trim();

  if (c.startsWith("#")) {
    const hex = c.slice(1);
    if (hex.length === 3) {
      const r = parseInt(hex[0] + hex[0], 16);
      const g = parseInt(hex[1] + hex[1], 16);
      const b = parseInt(hex[2] + hex[2], 16);
      if ([r, g, b].some((v) => Number.isNaN(v))) return null;
      return { r, g, b };
    }
    if (hex.length === 6) {
      const r = parseInt(hex.slice(0, 2), 16);
      const g = parseInt(hex.slice(2, 4), 16);
      const b = parseInt(hex.slice(4, 6), 16);
      if ([r, g, b].some((v) => Number.isNaN(v))) return null;
      return { r, g, b };
    }
  }
  return null;
}

function relativeLuminance(rgb: { r: number; g: number; b: number }): number {
  const srgb = [rgb.r, rgb.g, rgb.b].map((v) => v / 255);
  const lin = srgb.map((v) => (v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4)));
  return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2];
}

function getReadableTextColor(inputColor: string | null | undefined): string {
  const rgb = toRgb(inputColor);
  if (!rgb) return "#e5e5e5";
  const L = relativeLuminance(rgb);
  if (L > 0.8) return "#18181b";
  return inputColor || "#e5e5e5";
}

interface TreeNodeProps {
  node: MacchinaWithDetails;
  allNodes: MacchinaWithDetails[];
  level?: number;
  articlesByMacchina?: Record<number, ArticoloAssegnatoMacchina[]>;
  isCloning?: boolean;
  copiedNodeId?: number | null;
  onAdd: (parentId: number) => void;
  onEdit: (node: MacchinaWithDetails) => void;
  onDelete: (id: number) => void;
  onClone: (node: MacchinaWithDetails) => void;
  onCopy: (node: MacchinaWithDetails) => void;
  onPaste: (targetId: number) => void;
  onShowArticles?: (nodeId: number) => void;
  onDropArticle?: (macchinaId: number, article: unknown) => void;
}

export default function TreeNode({
  node,
  allNodes,
  level = 0,
  articlesByMacchina = {},
  isCloning = false,
  copiedNodeId,
  onAdd,
  onEdit,
  onDelete,
  onClone,
  onCopy,
  onPaste,
  onShowArticles,
  onDropArticle,
}: TreeNodeProps) {
  const [isExpanded, setIsExpanded] = useState(false);
  const [isDragOver, setIsDragOver] = useState(false);

  const children = allNodes.filter((n) => n.id_padre === node.id);
  const nodeArticles = articlesByMacchina[node.id] || [];

  const getTotalQuantity = (currentNode: MacchinaWithDetails): number => {
    const currentArticles = articlesByMacchina[currentNode.id] || [];
    const currentQty = currentArticles.reduce(
      (sum, art) => sum + (art.quantita || 0),
      0
    );

    const childNodes = allNodes.filter((n) => n.id_padre === currentNode.id);
    const childrenQty = childNodes.reduce(
      (sum, child) => sum + getTotalQuantity(child),
      0
    );

    return currentQty + childrenQty;
  };

  const totalQuantity = getTotalQuantity(node);

  const handleDrop = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(false);
    
    try {
      const data = e.dataTransfer.getData("application/json");
      if (data && onDropArticle) {
        const article = JSON.parse(data);
        onDropArticle(node.id, article);
      }
    } catch {
      // Ignore parsing errors
    }
  };

  const handleDragOver = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    e.dataTransfer.dropEffect = "move";
    setIsDragOver(true);
  };

  const handleDragLeave = (e: DragEvent<HTMLDivElement>) => {
    const relatedTarget = e.relatedTarget as Node | null;
    const currentTarget = e.currentTarget as Node;
    
    if (relatedTarget && currentTarget.contains(relatedTarget)) {
      return;
    }
    
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(false);
  };

  const handleDragEnter = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(true);
  };

  const safeTextColor = getReadableTextColor(node.colore_testo);

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

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

  return (
    <div 
      className="mb-1"
      style={{ marginLeft: `${level * 16}px` }}
    >
      <div
        className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all group
          ${getNodeTypeBg()}
          ${isDragOver ? "ring-2 ring-blue-500 bg-blue-900/50 scale-[1.02]" : ""}
          hover:bg-zinc-800/70`}
        onDragEnter={handleDragEnter}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
      >
        {children.length > 0 && (
          <button
            onClick={() => setIsExpanded(!isExpanded)}
            className="w-5 h-5 flex items-center justify-center text-zinc-400 hover:text-white transition-colors"
            title={isExpanded ? "Comprimi" : "Espandi"}
          >
            <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"
          style={{ color: safeTextColor }}
        >
          {node.nome}
        </span>

        {totalQuantity > 0 && (
          <button
            onClick={() => onShowArticles?.(node.id)}
            className="px-2 py-0.5 text-xs rounded bg-teal-900/50 text-teal-300 border border-teal-700/50 hover:bg-teal-800/50 transition-colors"
            title={`${totalQuantity} articoli assegnati`}
          >
            📦 {totalQuantity}
          </button>
        )}

        <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
          <button
            onClick={() => onAdd(node.id)}
            disabled={isCloning}
            className="p-1 rounded text-zinc-400 hover:text-green-400 hover:bg-green-900/30 transition-colors disabled:opacity-50"
            title="Aggiungi sotto-elemento"
          >
            <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>

          <button
            onClick={() => onEdit(node)}
            disabled={isCloning}
            className="p-1 rounded text-zinc-400 hover:text-blue-400 hover:bg-blue-900/30 transition-colors disabled:opacity-50"
            title="Modifica"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
            </svg>
          </button>

          <button
            onClick={() => onCopy(node)}
            disabled={isCloning}
            className="p-1 rounded text-zinc-400 hover:text-yellow-400 hover:bg-yellow-900/30 transition-colors disabled:opacity-50"
            title="Copia"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
            </svg>
          </button>

          <button
            onClick={() => onClone(node)}
            disabled={isCloning}
            className="p-1 rounded text-zinc-400 hover:text-purple-400 hover:bg-purple-900/30 transition-colors disabled:opacity-50"
            title="Clona con sotto-elementi"
          >
            {isCloning ? (
              <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>
            ) : (
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
              </svg>
            )}
          </button>

          {copiedNodeId && (
            <button
              onClick={() => onPaste(node.id)}
              disabled={isCloning}
              className="p-1 rounded text-zinc-400 hover:text-orange-400 hover:bg-orange-900/30 transition-colors disabled:opacity-50"
              title="Incolla"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
              </svg>
            </button>
          )}

          <button
            onClick={() => onDelete(node.id)}
            disabled={isCloning}
            className="p-1 rounded text-zinc-400 hover:text-red-400 hover:bg-red-900/30 transition-colors disabled:opacity-50"
            title="Elimina"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
            </svg>
          </button>
        </div>
      </div>

      {isExpanded && children.length > 0 && (
        <div className="mt-1">
          {children.map((child) => (
            <TreeNode
              key={child.id}
              node={child}
              allNodes={allNodes}
              level={level + 1}
              articlesByMacchina={articlesByMacchina}
              isCloning={isCloning}
              copiedNodeId={copiedNodeId}
              onAdd={onAdd}
              onEdit={onEdit}
              onDelete={onDelete}
              onClone={onClone}
              onCopy={onCopy}
              onPaste={onPaste}
              onShowArticles={onShowArticles}
              onDropArticle={onDropArticle}
            />
          ))}
        </div>
      )}
    </div>
  );
}
