"use client";
import { useReactFlow, Handle, Position } from "reactflow";

interface Analytics {
  sent: number;
  responded: number;
  dropped: number;
}

interface Props {
  id: string;
  selected: boolean;
  color: string;
  border: string;
  children: React.ReactNode;
  hideDefaultHandles?: boolean;
  customHandles?: React.ReactNode;
  noTarget?: boolean;
  noSource?: boolean;
  analytics?: Analytics;
}

export function NodeShell({
  id, selected, color, border, children,
  hideDefaultHandles, customHandles,
  noTarget, noSource, analytics,
}: Props) {
  const { setNodes, setEdges } = useReactFlow();

  function onDelete(e: React.MouseEvent) {
    e.preventDefault();
    e.stopPropagation();
    setNodes(ns => ns.filter(n => n.id !== id));
    setEdges(es => es.filter(e => e.source !== id && e.target !== id));
  }

  return (
    <div
      className="relative node-enter group/shell"
      style={{
        borderRadius: 18,
        border: `2px solid ${selected ? color : border}`,
        boxShadow: selected
          ? `0 0 0 3px ${color}40, 0 8px 24px ${color}20`
          : "0 2px 16px #0000000f",
        background: "#fff",
        overflow: "visible",
      }}
    >
      {/* ── ✕ Delete button — top-right, shows on node hover ── */}
      <button
        onClick={onDelete}
        onMouseDown={e => e.stopPropagation()}
        title="Delete block"
        className="
          nodrag nopan
          absolute z-20 -top-3 -right-3
          w-6 h-6 rounded-full
          bg-red-500 text-white border-2 border-white
          text-[11px] font-black leading-none
          flex items-center justify-center
          shadow-md
          opacity-0 scale-75
          group-hover/shell:opacity-100 group-hover/shell:scale-100
          transition-all duration-150
          hover:bg-red-600 active:scale-90
          cursor-pointer
        "
      >
        ✕
      </button>

      {/* ── Analytics badge — top-left, inside node so it zooms with canvas ── */}
      {analytics && (() => {
        const rate  = Math.round((analytics.responded / analytics.sent) * 100);
        const drop  = Math.round((analytics.dropped   / analytics.sent) * 100);
        const bg    = rate > 70 ? "#059669" : rate > 40 ? "#d97706" : "#dc2626";
        return (
          <div className="absolute -top-7 left-0 flex items-center gap-1 pointer-events-none z-10">
            <span className="text-white text-[10px] font-black px-2 py-0.5 rounded-full shadow-md"
              style={{ background: bg }}>
              {rate}% reply
            </span>
            <span className="text-white text-[10px] font-bold px-2 py-0.5 rounded-full shadow-md bg-gray-600">
              {analytics.sent} sent
            </span>
            {drop > 0 && (
              <span className="text-white text-[10px] font-bold px-2 py-0.5 rounded-full shadow-md bg-red-500">
                -{drop}% drop
              </span>
            )}
          </div>
        );
      })()}

      {children}

      {!hideDefaultHandles && (
        <>
          {/* ── TARGET handle (left) ── */}
          {!noTarget && (
            <div className="absolute left-0 top-1/2 -translate-y-1/2 -translate-x-1/2 z-10 group/th">
              <Handle
                type="target"
                position={Position.Left}
                style={{
                  width: 14, height: 14,
                  background: color, border: "3px solid #fff",
                  position: "static", transform: "none",
                }}
              />
              <span className="
                pointer-events-none absolute left-5 top-1/2 -translate-y-1/2
                bg-gray-800 text-white text-[9px] font-bold px-2 py-1 rounded-lg whitespace-nowrap
                opacity-0 group-hover/th:opacity-100 transition-opacity duration-150
              ">
                ← connect here
              </span>
            </div>
          )}

          {/* ── SOURCE handle (right) with "drag to link" pill ── */}
          {!noSource && (
            <div className="absolute right-0 top-1/2 -translate-y-1/2 translate-x-1/2 z-10 group/sh">
              <Handle
                type="source"
                position={Position.Right}
                style={{
                  width: 18, height: 18,
                  background: color, border: "3px solid #fff",
                  position: "static", transform: "none",
                  cursor: "crosshair",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}
              >
                <span
                  style={{
                    fontSize: 9, fontWeight: 900, color: "#fff",
                    pointerEvents: "none", userSelect: "none",
                  }}
                >
                  ⇢
                </span>
              </Handle>
              <span className="
                pointer-events-none absolute right-8 top-1/2 -translate-y-1/2
                bg-gray-800 text-white text-[9px] font-bold px-2 py-1 rounded-lg whitespace-nowrap
                opacity-0 group-hover/sh:opacity-100 transition-opacity duration-150
              ">
                drag to link →
              </span>
            </div>
          )}
        </>
      )}

      {customHandles}
    </div>
  );
}
