import type { ChartDrawing, ChartInteractionTool, DrawingToolType } from "@/lib/chart/drawings/types";
import { useState } from "react";

type DrawingToolbarProps = {
  activeTool: ChartInteractionTool;
  onToolChange: (tool: ChartInteractionTool) => void;
  selectedDrawing?: ChartDrawing | null;
};

type ToolGroup = {
  id: string;
  label: string;
  tools: { id: ChartInteractionTool; label: string }[];
};

const GROUPS: ToolGroup[] = [
  {
    id: "lines",
    label: "Lines",
    tools: [
      { id: "trend", label: "Trend" },
      { id: "arrow", label: "Arrow" },
      { id: "ray", label: "Ray" },
      { id: "horizontal", label: "H-Line" },
      { id: "horizontal_ray", label: "H-Ray" },
      { id: "vertical", label: "V-Line" },
      { id: "vertical_ray", label: "V-Ray" },
    ],
  },
  {
    id: "shapes",
    label: "Shapes",
    tools: [
      { id: "rectangle", label: "Rectangle" },
      { id: "circle", label: "Circle" },
      { id: "ellipse", label: "Ellipse" },
      { id: "arc", label: "Arc" },
      { id: "parallel_channel", label: "Channel" },
    ],
  },
  {
    id: "freeform",
    label: "Freeform",
    tools: [
      { id: "path", label: "Path" },
      { id: "pen", label: "Pen" },
      { id: "marker", label: "Marker" },
    ],
  },
  {
    id: "analysis",
    label: "Measure",
    tools: [
      { id: "measure", label: "Measure" },
      { id: "price_range", label: "Price range" },
      { id: "long_position", label: "Long" },
      { id: "short_position", label: "Short" },
    ],
  },
  {
    id: "annotation",
    label: "Text",
    tools: [
      { id: "text", label: "Text" },
      { id: "callout", label: "Callout" },
    ],
  },
  {
    id: "fib",
    label: "Fibonacci",
    tools: [{ id: "fibonacci", label: "Fib retracement" }],
  },
];

function toolLabel(tool: ChartInteractionTool): string {
  if (tool === "select") {
    return "Select";
  }
  if (tool === "delete") {
    return "Delete";
  }
  for (const g of GROUPS) {
    const hit = g.tools.find((t) => t.id === tool);
    if (hit) {
      return hit.label;
    }
  }
  return tool;
}

function selectedDrawingLabel(drawing: ChartDrawing): string {
  if (drawing.type === "text" || drawing.type === "callout") {
    const t = "text" in drawing ? drawing.text : "";
    return t ? `Selected: ${t.slice(0, 24)}${t.length > 24 ? "…" : ""}` : "Selected text";
  }
  return `Selected: ${drawing.type.replace(/_/g, " ")}`;
}

export function DrawingToolbar({ activeTool, onToolChange, selectedDrawing }: DrawingToolbarProps) {
  const [openGroup, setOpenGroup] = useState<string | null>(null);

  const pick = (id: ChartInteractionTool) => {
    onToolChange(id);
    setOpenGroup(null);
  };

  return (
    <div className="drawing-toolbar" role="toolbar" aria-label="Drawing tools">
      <button
        type="button"
        className={`drawing-tool-btn${activeTool === "select" ? " drawing-tool-active" : ""}`}
        aria-pressed={activeTool === "select"}
        onClick={() => pick("select")}
      >
        Select
      </button>
      {GROUPS.map((group) => {
        const activeInGroup = group.tools.some((t) => t.id === activeTool);
        return (
          <div key={group.id} className="drawing-tool-group">
            <button
              type="button"
              className={`drawing-tool-btn drawing-tool-group-btn${
                activeInGroup ? " drawing-tool-active" : ""
              }`}
              aria-expanded={openGroup === group.id}
              aria-haspopup="menu"
              onClick={() => setOpenGroup((g) => (g === group.id ? null : group.id))}
            >
              {activeInGroup ? toolLabel(activeTool) : group.label}
            </button>
            {openGroup === group.id && (
              <div className="drawing-tool-menu" role="menu">
                {group.tools.map((t) => (
                  <button
                    key={t.id}
                    type="button"
                    role="menuitem"
                    className={`drawing-tool-menu-item${
                      activeTool === t.id ? " drawing-tool-active" : ""
                    }`}
                    onClick={() => pick(t.id)}
                  >
                    {t.label}
                  </button>
                ))}
              </div>
            )}
          </div>
        );
      })}
      <button
        type="button"
        className={`drawing-tool-btn${activeTool === "delete" ? " drawing-tool-active" : ""}`}
        aria-pressed={activeTool === "delete"}
        onClick={() => pick("delete")}
      >
        Delete
      </button>
      {selectedDrawing ? (
        <span className="drawing-tool-selected" title={selectedDrawing.id}>
          {selectedDrawingLabel(selectedDrawing)}
        </span>
      ) : null}
      <span className="drawing-tool-hint">
        {activeTool === "path" || activeTool === "pen"
          ? "Click points · double-click to finish"
          : activeTool === "parallel_channel"
            ? "Three clicks: line, then width"
            : activeTool !== "select" && activeTool !== "delete"
              ? "Click chart to place anchors"
              : "Pan/zoom on chart · click drawing to move"}
      </span>
    </div>
  );
}

export function isInteractiveDrawingTool(
  tool: ChartInteractionTool,
): tool is DrawingToolType | "delete" {
  return tool !== "select";
}
