import { useState, useRef, useEffect } from "react";

interface Props {
  onEmojiSelect: (emoji: string) => void;
  disabled?: boolean;
}

// Compact emoji set organized by category — covers the most commonly used emojis
const EMOJI_CATEGORIES = [
  { name: "Smileys", emojis: ["😀","😃","😄","😁","😂","🤣","😊","😇","🙂","😉","😍","🥰","😘","😋","😎","🤩","🥳","😏","😒","😞","😔","😟","😕","😢","😭","😤","🤬","😡","🤯","😳","🥺","😱","😨","😰","🤗","🤔","🤫","🤭","😐","😑","😬","🙄","😴","🤮","🤢","🤧","😷","🤒"] },
  { name: "Gestures", emojis: ["👍","👎","👊","✊","🤛","🤜","👏","🙌","👐","🤝","🙏","💪","🤞","✌️","🤟","🤘","👌","🤙","👈","👉","👆","👇","☝️","✋","🤚","🖐️","🖖","👋","🤏","✍️"] },
  { name: "Hearts", emojis: ["❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❤️‍🔥","💕","💞","💓","💗","💖","💘","💝","💟","♥️"] },
  { name: "People", emojis: ["👶","👧","🧒","👦","👩","🧑","👨","👩‍🦱","👨‍🦱","👩‍🦰","👨‍🦰","👱‍♀️","👱‍♂️","👩‍🦳","👨‍🦳","👩‍🦲","👨‍🦲","🧔","👵","🧓","👴","🤴","👸","🎅","🤶"] },
  { name: "Animals", emojis: ["🐶","🐱","🐭","🐹","🐰","🦊","🐻","🐼","🐨","🐯","🦁","🐮","🐷","🐸","🐵","🙈","🙉","🙊","🐔","🐧","🐦","🦆","🦅","🦉","🦇","🐺","🐗","🐴","🦄","🐝","🐛","🦋","🐌","🐞","🐜"] },
  { name: "Food", emojis: ["🍎","🍊","🍋","🍌","🍉","🍇","🍓","🫐","🍈","🍒","🍑","🥭","🍍","🥥","🥝","🍅","🥑","🌮","🍕","🍔","🍟","🌭","🍿","🧁","🍰","🎂","🍩","🍪","🍫","🍬"] },
  { name: "Travel", emojis: ["🚗","🚕","🚌","🚎","🏎️","🚓","🚑","🚒","✈️","🚀","🛸","🚁","🛶","⛵","🚢","🏠","🏡","🏢","🏰","🗼","🗽","⛪","🕌","🛕","🏛️","⛩️","🗻","🌋","🏜️","🏝️"] },
  { name: "Objects", emojis: ["⌚","📱","💻","⌨️","🖥️","🖨️","🖱️","💡","🔦","📷","📹","🎥","📞","☎️","📺","📻","🎙️","🎧","🎬","💰","💳","💎","🔑","🔒","📦","📫","✏️","📝","📌","📎"] },
  { name: "Symbols", emojis: ["⭐","🌟","✨","💫","🔥","💥","💯","✅","❌","⭕","❗","❓","💤","💬","💭","🗯️","♻️","🔔","🎵","🎶","🏆","🥇","🥈","🥉","⚽","🏀","🏈","⚾","🎯","🎮"] },
  { name: "Flags", emojis: ["🏳️","🏴","🏁","🚩","🏳️‍🌈","🇺🇸","🇬🇧","🇨🇦","🇦🇺","🇫🇷","🇩🇪","🇮🇹","🇪🇸","🇧🇷","🇯🇵","🇰🇷","🇨🇳","🇮🇳","🇲🇽","🇷🇺"] },
];

export default function EmojiPicker({ onEmojiSelect, disabled }: Props) {
  const [open, setOpen] = useState(false);
  const [activeCategory, setActiveCategory] = useState(0);
  const [search, setSearch] = useState("");
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const handler = (e: KeyboardEvent) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("keydown", handler);
    return () => document.removeEventListener("keydown", handler);
  }, [open]);

  const filteredEmojis = search
    ? EMOJI_CATEGORIES.flatMap((c) => c.emojis)
    : EMOJI_CATEGORIES[activeCategory]?.emojis || [];

  return (
    <div ref={ref} className="vr-relative vr-inline-block">
      <button
        type="button"
        onClick={() => !disabled && setOpen(!open)}
        disabled={disabled}
        className="vr-w-8 vr-h-8 vr-flex vr-items-center vr-justify-center vr-rounded-md vr-text-gray-400 hover:vr-text-gray-600 hover:vr-bg-gray-100 vr-transition-colors vr-border-0 vr-bg-transparent vr-cursor-pointer disabled:vr-opacity-40 disabled:vr-cursor-not-allowed"
        title="Add emoji"
      >
        <i className="fa-regular fa-face-smile" style={{ fontSize: "15px" }} />
      </button>

      {open && (
        <div
          className="vr-absolute vr-z-50 vr-bg-white vr-border vr-border-gray-200 vr-rounded-xl vr-shadow-xl vr-overflow-hidden"
          style={{ bottom: "100%", left: 0, marginBottom: "4px", width: "320px" }}
        >
          {/* Search */}
          <div className="vr-p-2 vr-border-b vr-border-gray-100">
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search..."
              className="vr-w-full vr-px-2.5 vr-py-1.5 vr-text-xs vr-rounded-md vr-border vr-border-gray-200 vr-outline-none focus:vr-border-primary-300 vr-bg-gray-50"
              autoFocus
            />
          </div>

          {/* Category tabs */}
          {!search && (
            <div className="vr-flex vr-gap-0.5 vr-px-2 vr-py-1.5 vr-border-b vr-border-gray-100 vr-overflow-x-auto">
              {EMOJI_CATEGORIES.map((cat, i) => (
                <button
                  key={cat.name}
                  onClick={() => setActiveCategory(i)}
                  className={`vr-px-2 vr-py-1 vr-rounded vr-text-xs vr-font-medium vr-border-0 vr-cursor-pointer vr-whitespace-nowrap vr-transition-colors ${
                    activeCategory === i
                      ? "vr-bg-primary-50 vr-text-primary-600"
                      : "vr-bg-transparent vr-text-gray-500 hover:vr-bg-gray-100"
                  }`}
                >
                  {cat.emojis[0]} {cat.name}
                </button>
              ))}
            </div>
          )}

          {/* Emoji grid */}
          <div className="vr-p-2 vr-overflow-y-auto" style={{ maxHeight: "220px" }}>
            <div className="vr-grid vr-grid-cols-8 vr-gap-0.5">
              {filteredEmojis.map((emoji, i) => (
                <button
                  key={`${emoji}-${i}`}
                  onClick={() => { onEmojiSelect(emoji); }}
                  className="vr-w-8 vr-h-8 vr-flex vr-items-center vr-justify-center vr-rounded-md hover:vr-bg-gray-100 vr-transition-colors vr-border-0 vr-bg-transparent vr-cursor-pointer vr-text-lg"
                  title={emoji}
                >
                  {emoji}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
