"use client";
import { memo } from "react";
import { Handle, Position } from "reactflow";
import { NodeShell } from "./NodeShell";
import { KIND_META } from "./nodeTypes";

export const RetryNode = memo(function RetryNode({ id, selected, data }: any) {
  const m = KIND_META.retry;
  const delay = data.retryDelayMinutes ?? 1440;
  const delayLabel = delay >= 1440 ? `${Math.round(delay / 1440)}d` : delay >= 60 ? `${Math.round(delay / 60)}h` : `${delay}m`;

  const customHandles = (
    <>
      <Handle type="target" position={Position.Left}
        style={{ width: 14, height: 14, background: m.color, border: "3px solid #fff", left: -8, top: "50%" }} />
      <Handle id="responded" type="source" position={Position.Right}
        style={{ width: 14, height: 14, background: "#059669", border: "3px solid #fff", right: -8, top: 62 }} />
      <Handle id="escalate" type="source" position={Position.Right}
        style={{ width: 14, height: 14, background: "#dc2626", border: "3px solid #fff", right: -8, top: 110 }} />
    </>
  );

  return (
    <NodeShell id={id} selected={selected} color={m.color} border={m.border} analytics={data.analytics} hideDefaultHandles customHandles={customHandles}>
      <div className={`bg-gradient-to-r ${m.gradient} px-4 py-2.5 rounded-t-[14px] flex items-center gap-2`}>
        <span className="text-lg">{m.icon}</span>
        <div className="flex-1 min-w-0">
          <p className="text-white font-bold text-[12px] truncate">{data.label}</p>
          <p className="text-white/70 text-[10px]">{m.label}</p>
        </div>
        <span className="text-[9px] bg-white/20 text-white font-bold px-2 py-0.5 rounded-full">
          ×{data.maxRetries ?? 2}
        </span>
      </div>
      <div className="bg-white px-4 py-3 rounded-b-[14px]" style={{ width: 230 }}>
        <div className="space-y-1.5 pr-3">
          <div className="flex items-center gap-2 px-3 py-2 rounded-lg text-[11px] font-semibold border border-emerald-200 bg-emerald-50 text-emerald-700">
            <span>✅</span> Responded
          </div>
          <div className="flex items-center gap-2 px-3 py-2 rounded-lg text-[11px] font-semibold border border-red-200 bg-red-50 text-red-600">
            <span>🚨</span> Escalate (no reply × {data.maxRetries ?? 2})
          </div>
        </div>
        <p className="text-[10px] text-gray-400 mt-2 px-1">Retry every {delayLabel}</p>
      </div>
    </NodeShell>
  );
});
