"use client";

import { useEffect, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import ChatBoldIcon, { type ChatBoldIconName } from "./ChatBoldIcon";

export type AttachmentType = "image" | "video" | "file" | "location" | "camera";

interface AttachmentMenuProps {
  open: boolean;
  onClose: () => void;
  onSelect: (type: AttachmentType) => void;
  anchorRef?: React.RefObject<HTMLElement | null>;
}

const items: {
  type: AttachmentType;
  label: string;
  icon: ChatBoldIconName;
  color: string;
}[] = [
  { type: "camera", label: "دوربین", icon: "camera", color: "bg-red-500" },
  { type: "image", label: "گالری", icon: "gallery", color: "bg-purple-500" },
  { type: "video", label: "ویدیو", icon: "video", color: "bg-blue-500" },
  { type: "file", label: "فایل", icon: "file", color: "bg-orange-500" },
  { type: "location", label: "موقعیت", icon: "location", color: "bg-green-500" },
];

export default function AttachmentMenu({
  open,
  onClose,
  onSelect,
  anchorRef,
}: AttachmentMenuProps) {
  const menuRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const handleClick = (e: MouseEvent) => {
      const target = e.target as Node;
      if (
        menuRef.current &&
        !menuRef.current.contains(target) &&
        !anchorRef?.current?.contains(target)
      ) {
        onClose();
      }
    };
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, [open, onClose, anchorRef]);

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          ref={menuRef}
          initial={{ opacity: 0, y: 12, scale: 0.95 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          exit={{ opacity: 0, y: 8, scale: 0.95 }}
          transition={{ duration: 0.25, ease: [0.25, 0.46, 0.45, 0.94] }}
          className="glass-panel absolute bottom-full left-0 z-[60] mb-3 min-w-[200px] rounded-2xl p-2 shadow-xl"
        >
          {items.map((item, i) => (
            <motion.button
              key={item.type}
              type="button"
              initial={{ opacity: 0, x: -8 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: i * 0.04 }}
              onClick={() => {
                onSelect(item.type);
                onClose();
              }}
              className="gentle-transition flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-right hover:bg-black/5 active:scale-[0.98] dark:hover:bg-white/10"
            >
              <span
                className={`flex h-10 w-10 items-center justify-center rounded-full text-white ${item.color}`}
              >
                <ChatBoldIcon name={item.icon} size={22} className="text-white" />
              </span>
              <span className="text-sm font-medium">{item.label}</span>
            </motion.button>
          ))}
        </motion.div>
      )}
    </AnimatePresence>
  );
}
