"use client";

import { useRef, useState, useEffect } from "react";
import { GraphNode, PRIORITY_LABELS, PRIORITY_COLORS, getPrefixLabel } from "@/lib/types";
import { formatRelativeTime } from "@/lib/utils";

interface BeadTooltipProps {
  node: GraphNode;
  x: number;
  y: number;
  prefixColor: string;
  allNodes: GraphNode[];
  theme?: string;
}

export function BeadTooltip({ node, x, y, prefixColor, allNodes, theme }: BeadTooltipProps) {
  const COLORS = theme === "dark" ? {
    bg: "#18181b",        // zinc-900
    border: "#3f3f46",    // zinc-700
    borderLight: "#27272a", // zinc-800
    shadow: "rgba(0,0,0,0.3)",
    text: "#f4f4f5",      // zinc-100
    textMuted: "#a1a1aa",  // zinc-400
    textDim: "#71717a",    // zinc-500
  } : {
    bg: "#FFFFFF",
    border: "#E5E7EB",
    borderLight: "#F3F4F6",
    shadow: "rgba(0,0,0,0.08)",
    text: "#131316",
    textMuted: "#737680",
    textDim: "#7F818B",
  };
  const ref = useRef<HTMLDivElement>(null);
  const [pos, setPos] = useState({ x: 0, y: 0 });

  useEffect(() => {
    if (!ref.current) return;
    const tt = ref.current.getBoundingClientRect();
    const pad = 14;

    // Prefer placing above and to the right of cursor
    let nx = x + pad;
    let ny = y - tt.height - pad;

    // Clamp to viewport edges
    if (nx + tt.width > window.innerWidth - 16) {
      nx = x - tt.width - pad;
    }
    if (nx < 16) nx = 16;
    if (ny < 16) {
      ny = y + pad + 8;
    }
    if (ny + tt.height > window.innerHeight - 16) {
      ny = window.innerHeight - tt.height - 16;
    }

    setPos({ x: nx, y: ny });
  }, [x, y]);

  // Resolve blocker IDs to short titles
  const blockers = node.dependentIds
    .map((id) => {
      const blockerNode = allNodes.find((n) => n.id === id);
      return blockerNode ? { id, title: blockerNode.title } : { id, title: id };
    })
    .filter(Boolean);

  const priorityLabel = PRIORITY_LABELS[node.priority] || `P${node.priority}`;
  const priorityColor = PRIORITY_COLORS[node.priority] || "#a1a1aa";

  const labelStyle: React.CSSProperties = {
    fontSize: 10,
    fontWeight: 600,
    letterSpacing: 1.5,
    textTransform: "uppercase",
    color: theme === "dark" ? "#71717a" : "#7F818B",
    marginBottom: 3,
  };

  const valueStyle: React.CSSProperties = {
    fontSize: 12,
    color: theme === "dark" ? "#a1a1aa" : "#737680",
    lineHeight: 1.45,
  };

  return (
    <div
      ref={ref}
      className="bead-tooltip"
      style={{
        position: "fixed",
        left: pos.x,
        top: pos.y,
        width: 280,
        zIndex: 100,
        pointerEvents: "none",
        background: COLORS.bg,
        border: `1px solid ${COLORS.border}`,
        boxShadow: `0 8px 32px ${COLORS.shadow}, 0 2px 8px ${COLORS.shadow}`,
        borderRadius: 8,
        padding: "16px 18px",
        animation: "beadTooltipFade 0.2s ease",
      }}
    >
      {/* Accent bar */}
      <div
        style={{
          width: 24,
          height: 2,
          background: prefixColor,
          opacity: 0.5,
          marginBottom: 8,
          borderRadius: 1,
        }}
      />

      {/* Prefix + ID */}
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 6 }}>
        <span
          style={{
            fontSize: 10,
            fontWeight: 600,
            color: prefixColor,
            letterSpacing: 0.5,
            textTransform: "uppercase",
          }}
        >
          {getPrefixLabel(node.prefix)}
        </span>
        <span
          style={{
            fontSize: 10,
            fontFamily: "monospace",
            color: COLORS.textDim,
          }}
        >
          {node.id}
        </span>
      </div>

      {/* Title */}
      <div
        style={{
          fontSize: 14,
          fontWeight: 600,
          color: COLORS.text,
          lineHeight: 1.25,
          marginBottom: 12,
          overflow: "hidden",
          display: "-webkit-box",
          WebkitLineClamp: 2,
          WebkitBoxOrient: "vertical",
        }}
      >
        {node.title}
      </div>

      {/* Labels */}
      {node.labels.length > 0 && (
        <div style={{ display: "flex", flexWrap: "wrap", gap: 4, marginBottom: 10 }}>
          {node.labels.slice(0, 3).map((label) => (
            <span
              key={label}
              style={{
                fontSize: 10,
                fontWeight: 500,
                color: theme === "dark" ? "#a1a1aa" : "#52525b",
                backgroundColor: theme === "dark" ? "#27272a" : "#f4f4f5",
                border: theme === "dark" ? "1px solid #3f3f46" : "1px solid #e4e4e7",
                borderRadius: 9999,
                padding: "1px 7px",
                lineHeight: "16px",
              }}
            >
              {label}
            </span>
          ))}
          {node.labels.length > 3 && (
            <span style={{ fontSize: 10, color: "#a1a1aa", lineHeight: "18px" }}>
              +{node.labels.length - 3} more
            </span>
          )}
        </div>
      )}

      {/* Metadata rows */}
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {/* Estimate */}
        {node.estimatedMinutes != null && (
          <div>
            <div style={labelStyle}>Estimate</div>
            <div style={valueStyle}>⏱ {node.estimatedMinutes}m</div>
          </div>
        )}

        {/* Created */}
        <div>
          <div style={labelStyle}>Created</div>
          <div style={valueStyle}>{formatRelativeTime(node.createdAt)}</div>
        </div>

        {/* Owner */}
        {node.owner && (
          <div>
            <div style={labelStyle}>Owner</div>
            <div style={valueStyle}>{node.owner}</div>
          </div>
        )}

        {/* Assignee */}
        {(node.assignee || node.createdBy) && (
          <div>
            {node.assignee && (
              <>
                <div style={labelStyle}>Assignee</div>
                <div style={valueStyle}>{node.assignee}</div>
              </>
            )}
            {node.createdBy && !node.assignee && (
              <>
                <div style={labelStyle}>Created by</div>
                <div style={valueStyle}>{node.createdBy}</div>
              </>
            )}
            {node.createdBy && node.assignee && node.createdBy !== node.assignee && (
              <>
                <div style={{ ...labelStyle, marginTop: 4 }}>Created by</div>
                <div style={valueStyle}>{node.createdBy}</div>
              </>
            )}
          </div>
        )}

        {/* Blocked by */}
        <div>
          <div style={labelStyle}>Blocked by</div>
          {blockers.length === 0 ? (
            <div style={{ ...valueStyle, color: "#10b981" }}>None</div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
              {blockers.map((b) => (
                <div key={b.id} style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                  <span
                    style={{
                      fontSize: 10,
                      fontFamily: "monospace",
                      color: COLORS.textDim,
                      flexShrink: 0,
                    }}
                  >
                    {b.id}
                  </span>
                  <span
                    style={{
                      fontSize: 12,
                      color: COLORS.textMuted,
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                      whiteSpace: "nowrap",
                    }}
                  >
                    {b.title}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Priority */}
        <div style={{ borderTop: `1px solid ${COLORS.borderLight}`, paddingTop: 8 }}>
          <div style={labelStyle}>Priority</div>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <div
              style={{
                width: 8,
                height: 8,
                borderRadius: "50%",
                background: priorityColor,
                flexShrink: 0,
              }}
            />
            <span style={valueStyle}>{priorityLabel}</span>
          </div>
        </div>
      </div>
    </div>
  );
}