import { Popover } from "@mantine/core";
import { useEffect, useRef } from "react";
import data from "@emoji-mart/data";
import { Picker } from "emoji-mart";

interface Props {
  opened: boolean;
  onClose: () => void;
  onSelect: (emoji: string) => void;
  target: React.ReactNode;
}

export function StickerPicker({ opened, onClose, onSelect, target }: Props) {
  return (
    <Popover
      opened={opened}
      onChange={(o) => { if (!o) onClose(); }}
      onDismiss={onClose}
      position="bottom-start"
      withArrow
      shadow="md"
      withinPortal
      closeOnClickOutside
      closeOnEscape
      trapFocus={false}
    >
      <Popover.Target>{target}</Popover.Target>
      <Popover.Dropdown p={0} style={{ background: "transparent", border: "none" }}>
        <PickerInner onSelect={(emoji) => { onSelect(emoji); onClose(); }} />
      </Popover.Dropdown>
    </Popover>
  );
}

function PickerInner({ onSelect }: { onSelect: (emoji: string) => void }) {
  const ref = useRef<HTMLDivElement | null>(null);
  const instanceRef = useRef<unknown>(null);
  const onSelectRef = useRef(onSelect);
  onSelectRef.current = onSelect;

  useEffect(() => {
    if (!ref.current) return;
    instanceRef.current = new Picker({
      data,
      onEmojiSelect: (e: { native?: string; shortcodes?: string }) => {
        const cb = onSelectRef.current;
        if (e.native) cb(e.native);
        else if (e.shortcodes) cb(e.shortcodes);
      },
      theme: "dark",
      previewPosition: "none",
      skinTonePosition: "search",
      autoFocus: true,
      maxFrequentRows: 2,
      ref,
    });
    return () => {
      if (ref.current) ref.current.innerHTML = "";
      instanceRef.current = null;
    };
  }, []);

  return <div ref={ref} />;
}
