"use client";

import { useEffect, useRef, useState } from "react";
import { Baseline, Highlighter, ChevronDown } from "lucide-react";
import { type EditorComponentProps, type ColorOption } from "./types";
import { usePopoverPosition, PopoverPortal } from "./usePopoverPosition";

const TEXT_COLORS: ColorOption[] = [
  { label: "Default", value: "" },
  { label: "Gray", value: "#6b7280" },
  { label: "Red", value: "#ef4444" },
  { label: "Orange", value: "#f97316" },
  { label: "Amber", value: "#f59e0b" },
  { label: "Green", value: "#22c55e" },
  { label: "Teal", value: "#14b8a6" },
  { label: "Blue", value: "#3b82f6" },
  { label: "Indigo", value: "#6366f1" },
  { label: "Purple", value: "#a855f7" },
  { label: "Pink", value: "#ec4899" },
];

const HIGHLIGHT_COLORS: ColorOption[] = [
  { label: "None", value: "" },
  { label: "Yellow", value: "#fef08a" },
  { label: "Green", value: "#bbf7d0" },
  { label: "Blue", value: "#bfdbfe" },
  { label: "Purple", value: "#e9d5ff" },
  { label: "Pink", value: "#fbcfe8" },
  { label: "Orange", value: "#fed7aa" },
];

interface SwatchGridProps {
  options: ColorOption[];
  onSelect: (value: string) => void;
  activeValue?: string;
}

function SwatchGrid({ options, onSelect, activeValue }: SwatchGridProps) {
  return (
    <div className="grid grid-cols-6 gap-1.5 p-2">
      {options.map((opt) => {
        const isActive = opt.value === activeValue;
        const isEmpty = opt.value === "";
        return (
          <button
            key={opt.label}
            type="button"
            title={opt.label}
            onClick={() => onSelect(opt.value)}
            className={`
              relative h-7 w-7 rounded-full border
              transition-transform hover:scale-110
              ${isActive ? "ring-2 ring-indigo-500 ring-offset-1 ring-offset-white" : ""}
              ${isEmpty ? "border-zinc-300 " : "border-black/10"}
            `}
            style={{
              backgroundColor: isEmpty ? "transparent" : opt.value,
              backgroundImage: isEmpty
                ? "linear-gradient(45deg, transparent 45%, currentColor 45%, currentColor 55%, transparent 55%)"
                : undefined,
              color: isEmpty ? "#ef4444" : undefined,
            }}
          />
        );
      })}
    </div>
  );
}

/**
 * Combined text-color and highlight-color picker. Two tabs in one popover
 * to keep the toolbar compact on mobile.
 *
 * Portaled to `document.body` with auto-flip positioning so it's never
 * clipped by a parent modal's overflow.
 */
export default function ColorPicker({ editor }: EditorComponentProps) {
  const [open, setOpen] = useState(false);
  const [tab, setTab] = useState<"text" | "highlight">("text");

  const triggerRef = useRef<HTMLButtonElement>(null);
  const popoverRef = useRef<HTMLDivElement>(null);

  const position = usePopoverPosition(triggerRef, open, popoverRef, {
    estimatedWidth: 224,
    estimatedHeight: 140,
  });

  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      const target = e.target as Node;
      if (
        triggerRef.current &&
        !triggerRef.current.contains(target) &&
        popoverRef.current &&
        !popoverRef.current.contains(target)
      ) {
        setOpen(false);
      }
    }
    function handleEscape(e: KeyboardEvent) {
      if (e.key === "Escape") setOpen(false);
    }
    document.addEventListener("mousedown", handleClickOutside);
    document.addEventListener("keydown", handleEscape);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.removeEventListener("keydown", handleEscape);
    };
  }, []);

  if (!editor) return null;

  const activeTextColor: string = editor.getAttributes("textStyle").color ?? "";
  const activeHighlight: string = editor.getAttributes("highlight").color ?? "";

  const handleTextColor = (value: string) => {
    if (value === "") {
      editor.chain().focus().unsetColor().run();
    } else {
      editor.chain().focus().setColor(value).run();
    }
  };

  const handleHighlight = (value: string) => {
    if (value === "") {
      editor.chain().focus().unsetHighlight().run();
    } else {
      editor.chain().focus().setHighlight({ color: value }).run();
    }
  };

  return (
    <div className="relative shrink-0">
      <button
        ref={triggerRef}
        type="button"
        onClick={() => setOpen((o) => !o)}
        title="Text color & highlight"
        aria-haspopup="dialog"
        aria-expanded={open}
        className="
          flex h-8 sm:h-9 items-center gap-0.5 rounded-md px-1.5
          text-zinc-600 transition-colors hover:bg-zinc-100
          
        "
      >
        <Baseline className="h-4 w-4" style={{ color: activeTextColor || undefined }} />
        <ChevronDown className="h-3 w-3 opacity-60" />
      </button>

      <PopoverPortal open={open} position={position} popoverRef={popoverRef}>
        <div
          className="
            w-56 rounded-md border border-zinc-200 bg-white shadow-lg
            
          "
        >
          <div className="flex border-b border-zinc-200 ">
            <button
              type="button"
              onClick={() => setTab("text")}
              className={`flex flex-1 items-center justify-center gap-1.5 py-2 text-xs font-medium ${
                tab === "text"
                  ? "border-b-2 border-indigo-500 text-indigo-600 "
                  : "text-zinc-500 "
              }`}
            >
              <Baseline className="h-3.5 w-3.5" />
              Text
            </button>
            <button
              type="button"
              onClick={() => setTab("highlight")}
              className={`flex flex-1 items-center justify-center gap-1.5 py-2 text-xs font-medium ${
                tab === "highlight"
                  ? "border-b-2 border-indigo-500 text-indigo-600 "
                  : "text-zinc-500 "
              }`}
            >
              <Highlighter className="h-3.5 w-3.5" />
              Highlight
            </button>
          </div>

          {tab === "text" ? (
            <SwatchGrid
              options={TEXT_COLORS}
              activeValue={activeTextColor}
              onSelect={handleTextColor}
            />
          ) : (
            <SwatchGrid
              options={HIGHLIGHT_COLORS}
              activeValue={activeHighlight}
              onSelect={handleHighlight}
            />
          )}
        </div>
      </PopoverPortal>
    </div>
  );
}
