"use client";

import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";

export interface RadialMenuItem {
  id: string;
  icon: React.ReactNode;
  label: string;
  onClick: () => void;
  disabled?: boolean;
  destructive?: boolean;
}

interface RadialMenuProps {
  items: RadialMenuItem[];
  isOpen: boolean;
  position: { x: number; y: number };
  onClose: () => void;
  size?: number;
}

export function RadialMenu({
  items,
  isOpen,
  position,
  onClose,
  size = 200,
}: RadialMenuProps) {
  const [mounted, setMounted] = useState(false);
  const [activeIndex, setActiveIndex] = useState<number>(-1);
  const [animatingIn, setAnimatingIn] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (isOpen) {
      requestAnimationFrame(() => requestAnimationFrame(() => setAnimatingIn(true)));
    } else {
      setAnimatingIn(false);
    }
  }, [isOpen]);

  useEffect(() => {
    if (!isOpen) return;
    setActiveIndex(-1);

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onClose();
        return;
      }
      if (e.key === "Enter" && activeIndex >= 0 && activeIndex < items.length) {
        e.preventDefault();
        const item = items[activeIndex];
        if (!item.disabled) {
          item.onClick();
          onClose();
        }
        return;
      }
      if (e.key === "ArrowRight" || e.key === "ArrowDown") {
        e.preventDefault();
        setActiveIndex((prev) => {
          let next = prev + 1;
          if (next >= items.length) next = 0;
          let loops = 0;
          while (items[next]?.disabled && loops < items.length) {
            next = next + 1 >= items.length ? 0 : next + 1;
            loops++;
          }
          return next;
        });
        return;
      }
      if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
        e.preventDefault();
        setActiveIndex((prev) => {
          let next = prev - 1;
          if (next < 0) next = items.length - 1;
          let loops = 0;
          while (items[next]?.disabled && loops < items.length) {
            next = next - 1 < 0 ? items.length - 1 : next - 1;
            loops++;
          }
          return next;
        });
        return;
      }
    };

    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [isOpen, activeIndex, items, onClose]);

  const radius = size / 2 - 28;
  const center = size / 2;

  if (!mounted) return null;

  return createPortal(
    <>
      <div
        className={cn(
          "fixed inset-0 z-[9998] bg-black/20 cursor-pointer transition-opacity duration-200",
          animatingIn ? "opacity-100" : "opacity-0 pointer-events-none"
        )}
        onClick={onClose}
      />

      <div
        ref={menuRef}
        className="fixed z-[9999]"
        style={{
          left: position.x - center,
          top: position.y - center,
          width: size,
          height: size,
        }}
        role="menu"
        aria-label="Action menu"
      >
        <div
          className={cn(
            "absolute rounded-full flex items-center justify-center transition-all duration-200 ease-out will-change-transform",
            animatingIn ? "scale-100 opacity-100" : "scale-0 opacity-0"
          )}
          style={{
            left: center - 24,
            top: center - 24,
            width: 48,
            height: 48,
          }}
        >
          <button
            className="w-12 h-12 rounded-full bg-background border border-border shadow-lg flex items-center justify-center hover:bg-muted transition-colors cursor-pointer"
            onClick={onClose}
            aria-label="Close menu"
          >
            <X className="w-5 h-5 text-muted-foreground" />
          </button>
        </div>

        {items.map((item, index) => {
          const angle = (index / items.length) * 2 * Math.PI - Math.PI / 2;
          const x = center + radius * Math.cos(angle);
          const y = center + radius * Math.sin(angle);
          const itemSize = 40;

          return (
            <div
              key={item.id}
              className={cn(
                "absolute transition-all duration-200 ease-out will-change-transform",
                animatingIn ? "scale-100 opacity-100" : "scale-0 opacity-0"
              )}
              style={{
                left: x - itemSize / 2,
                top: y - itemSize / 2,
                width: itemSize,
                height: itemSize,
                transitionDelay: animatingIn ? `${index * 35}ms` : "0ms",
              }}
            >
              <button
                className={cn(
                  "group relative flex items-center justify-center w-full h-full rounded-full shadow-lg border border-border transition-all duration-150 cursor-pointer focus:outline-none",
                  item.disabled
                    ? "opacity-30 cursor-not-allowed bg-muted"
                    : item.destructive
                      ? "bg-destructive/10 text-destructive hover:scale-125 hover:bg-destructive hover:text-destructive-foreground hover:border-destructive"
                      : "bg-background text-foreground hover:scale-125 hover:bg-primary hover:text-primary-foreground hover:border-primary",
                  activeIndex === index && !item.disabled && "scale-125 ring-2 ring-primary"
                )}
                disabled={item.disabled}
                onClick={(e) => {
                  e.stopPropagation();
                  if (item.disabled) return;
                  item.onClick();
                  onClose();
                }}
                onMouseEnter={() => setActiveIndex(index)}
                onMouseLeave={() => setActiveIndex(-1)}
                onFocus={() => setActiveIndex(index)}
                onBlur={() => setActiveIndex(-1)}
                role="menuitem"
                aria-label={item.label}
                tabIndex={activeIndex === index ? 0 : -1}
              >
                <span className="w-5 h-5 flex items-center justify-center [&>svg]:w-full [&>svg]:h-full">
                  {item.icon}
                </span>
                <span
                  className={cn(
                    "absolute -bottom-7 left-1/2 -translate-x-1/2 whitespace-nowrap text-[11px] font-medium leading-tight text-foreground bg-background/95 px-1.5 py-0.5 rounded shadow-sm border border-border/50",
                    "opacity-0 group-hover:opacity-100 transition-opacity duration-100 pointer-events-none",
                    activeIndex === index && !item.disabled && "opacity-100"
                  )}
                >
                  {item.label}
                </span>
              </button>
            </div>
          );
        })}
      </div>
    </>,
    document.body
  );
}
