"use client";

import { memo } from "react";
import { Handle, Position, type NodeProps } from "@xyflow/react";
import { COMPONENT_BY_TYPE, portSide, portRole, portLabel, nodeSize } from "@/lib/componentMeta";
import { mediaColor, mediaForPort } from "@/lib/mediaStyle";
import { effectiveSide, type Side } from "@/lib/orientation";
import type { EntropykNodeData } from "@/store/diagramStore";
import { hxFamily } from "@/lib/hxFamily";
import { ComponentIcon } from "./ComponentIcon";

const SIDE_POSITION: Record<Side, Position> = {
  left: Position.Left,
  right: Position.Right,
  top: Position.Top,
  bottom: Position.Bottom,
};

function EntropykNode({ data, selected }: NodeProps) {
  const d = data as unknown as EntropykNodeData;
  const meta = COMPONENT_BY_TYPE[d.type];
  const { w: BOX_W, h: BOX_H } = nodeSize(d.type);
  const rotation = d.rotation ?? 0;
  const flipH = !!d.flipH;
  const flipV = !!d.flipV;
  const isController = d.type === "SaturatedController";
  const family = hxFamily(d.type);

  if (!meta) {
    return (
      <div className="rounded border border-[var(--hot)] bg-white px-2 py-1 text-[11px] text-[var(--hot)]">
        Unknown: {d.type}
      </div>
    );
  }

  const accent = family?.accent ?? meta.color;

  const placement: Record<string, { side: Side; offset: number }> = {};
  for (const port of meta.ports) {
    const side = effectiveSide(portSide(port) as Side, rotation, flipH, flipV);
    const peers = meta.ports.filter(
      (p) => effectiveSide(portSide(p) as Side, rotation, flipH, flipV) === side,
    );
    const idx = peers.indexOf(port);
    placement[port] = {
      side,
      offset: peers.length === 1 ? 0.5 : (idx + 1) / (peers.length + 1),
    };
  }

  const iconTransform = [
    rotation ? `rotate(${rotation}deg)` : "",
    flipH ? "scaleX(-1)" : "",
    flipV ? "scaleY(-1)" : "",
  ]
    .filter(Boolean)
    .join(" ");

  return (
    <div className="flex flex-col items-center" style={{ width: BOX_W }}>
      {/* Symbol IS the node — selection is a CAD marquee, not a card */}
      <div
        className="ek-node relative"
        style={{
          width: BOX_W,
          height: BOX_H,
          outline: selected ? "1.5px dashed var(--accent)" : "1.5px dashed transparent",
          outlineOffset: 4,
        }}
      >
        {isController ? (
          <div className="h-full w-full overflow-hidden rounded-[3px] border border-[var(--line-strong)] bg-white">
            <ControlNodeFace data={d} />
          </div>
        ) : (
          <div
            className="h-full w-full"
            style={{ transform: iconTransform || undefined }}
          >
            <ComponentIcon type={d.type} color={accent} />
          </div>
        )}

        {meta.ports.map((port) => {
          const { side, offset } = placement[port];
          const horizontal = side === "left" || side === "right";
          const kind = mediaForPort({ data: d }, port);
          const c = mediaColor(kind);
          const style: React.CSSProperties = {
            ...(horizontal ? { top: `${offset * 100}%` } : { left: `${offset * 100}%` }),
            borderColor: c,
            background: c,
          };
          return (
            <Handle
              key={port}
              type={portRole(port)}
              position={SIDE_POSITION[side]}
              id={port}
              style={style}
              isConnectable
              title={`${port} · ${kind}`}
              className="media-handle"
            />
          );
        })}

        {/* Port tags sit INSIDE the symbol bounds — never collide with names */}
        {meta.ports.length > 2 &&
          meta.ports.map((port) => {
            const { side, offset } = placement[port];
            const horizontal = side === "left" || side === "right";
            const style: React.CSSProperties = horizontal
              ? { top: `${offset * 100}%`, transform: "translateY(-50%)", [side]: 8 }
              : { left: `${offset * 100}%`, transform: "translateX(-50%)", [side]: 7 };
            return (
              <span
                key={`t-${port}`}
                className="mono pointer-events-none absolute text-[6.5px] uppercase tracking-wide text-[var(--ink-faint)]"
                style={style}
              >
                {portLabel(port)}
              </span>
            );
          })}
      </div>

      <div className="mt-1.5 flex max-w-[200px] flex-col items-center leading-tight">
        {!isController && (
          <span className="mono truncate text-[10.5px] text-[var(--ink)]">{d.name}</span>
        )}
        <span className="truncate text-[8.5px] text-[var(--ink-faint)]">
          {isController ? "override control" : meta.label} · C{d.circuit}
        </span>
      </div>
    </div>
  );
}

function ControlNodeFace({ data }: { data: EntropykNodeData }) {
  const p = data.params;
  const measure = `${String(p.measure_component ?? "—")}.${shortOutput(String(p.measure_output ?? "—"))}`;
  const actuator = `${String(p.actuator_component ?? "—")}.${String(p.actuator_factor ?? "—")}`;
  const target = formatControlNumber(p.target);
  const bounds = `${formatControlNumber(p.min)}…${formatControlNumber(p.max)}`;
  const objectiveCount = controlObjectiveCount(p.objectives_json);

  return (
    <div className="flex h-full w-full flex-col overflow-hidden text-left">
      <div className="flex items-center justify-between bg-[#4c1d95] px-2 py-1 text-white">
        <span className="mono max-w-[122px] truncate text-[10px] font-semibold">{data.name}</span>
        <span className="rounded bg-white/20 px-1 py-0.5 text-[7px] font-bold uppercase tracking-wide">
          SS
        </span>
      </div>
      <div className="grid flex-1 grid-cols-[1fr_44px_1fr] items-stretch bg-[#f5f3ff]">
        <div className="flex min-w-0 flex-col justify-center px-2">
          <span className="text-[7px] font-semibold uppercase tracking-[0.08em] text-[#6b5b8c]">
            Controlled
          </span>
          <span className="mono truncate text-[9px] font-semibold text-[#2e1f4a]">{measure}</span>
          <span className="mono text-[8px] text-[#6b5b8c]">SP {target}</span>
        </div>
        <div className="flex flex-col items-center justify-center border-x border-[#ddd6fe] bg-[#ede9fe]">
          <span className="text-[7px] font-bold uppercase text-[#5b21b6]">Select</span>
          <span className="mono mt-0.5 grid h-5 min-w-5 place-items-center rounded-full bg-[#5b21b6] px-1 text-[9px] font-bold text-white">
            {objectiveCount}
          </span>
        </div>
        <div className="flex min-w-0 flex-col justify-center px-2">
          <span className="text-[7px] font-semibold uppercase tracking-[0.08em] text-[#6b5b8c]">
            Actuator
          </span>
          <span className="mono truncate text-[9px] font-semibold text-[#2e1f4a]">{actuator}</span>
          <span className="mono text-[8px] text-[#6b5b8c]">{bounds}</span>
        </div>
      </div>
    </div>
  );
}

function controlObjectiveCount(value: number | string | boolean | undefined): number {
  if (typeof value !== "string") return 0;
  try {
    const parsed: unknown = JSON.parse(value);
    return Array.isArray(parsed) ? parsed.length : 0;
  } catch {
    return 0;
  }
}

function shortOutput(output: string): string {
  const labels: Record<string, string> = {
    saturationTemperature: "Tsat",
    heatTransferRate: "Qdot",
    massFlowRate: "mdot",
    temperature: "T",
    pressure: "P",
    capacity: "Q",
    superheat: "SH",
    subcooling: "SC",
  };
  return labels[output] ?? output;
}

function formatControlNumber(value: number | string | boolean | undefined): string {
  return typeof value === "number" && Number.isFinite(value) ? Number(value.toPrecision(4)).toString() : "—";
}

export default memo(EntropykNode, (prev, next) => {
  const a = prev.data as unknown as EntropykNodeData;
  const b = next.data as unknown as EntropykNodeData;
  return (
    prev.selected === next.selected &&
    a.type === b.type &&
    a.name === b.name &&
    a.circuit === b.circuit &&
    (a.rotation ?? 0) === (b.rotation ?? 0) &&
    !!a.flipH === !!b.flipH &&
    !!a.flipV === !!b.flipV &&
    a.params === b.params
  );
});
