import React, { useCallback, useEffect, useRef, useState } from 'react'
import EmojiMartPicker from '../common/EmojiMartPicker'
import extractNativeEmoji from '../common/extractNativeEmoji'
import isEventWithinNode from '../common/isEventWithinNode'
import loadEmojiMartData from '../common/loadEmojiMartData'

/**
 * A button that opens a floating emoji picker.
 * When the user selects an emoji, `onEmojiSelect(emojiNative)` is called
 * with the native Unicode character.
 *
 * Props:
 *   onEmojiSelect  (string) → void   Called with the emoji character
 *   disabled       boolean           Disables the button
 *   className      string            Additional classes for the trigger button
 */
export default function EmojiPickerButton({ onEmojiSelect, disabled = false, className = '' }) {
  const [open, setOpen] = useState(false)
  const [pickerData, setPickerData] = useState(null)
  const wrapRef = useRef(null)

  useEffect(() => {
    if (!open || pickerData) return

    let cancelled = false

    loadEmojiMartData().then((data) => {
      if (!cancelled) {
        setPickerData(data)
      }
    })

    return () => {
      cancelled = true
    }
  }, [open, pickerData])

  // Close on outside click
  useEffect(() => {
    if (!open) return

    function handleClick(e) {
      if (!isEventWithinNode(e, wrapRef.current)) {
        setOpen(false)
      }
    }

    document.addEventListener('mousedown', handleClick)
    return () => document.removeEventListener('mousedown', handleClick)
  }, [open])

  // Close on Escape
  useEffect(() => {
    if (!open) return

    function handleKey(e) {
      if (e.key === 'Escape') setOpen(false)
    }

    document.addEventListener('keydown', handleKey)
    return () => document.removeEventListener('keydown', handleKey)
  }, [open])

  const handleSelect = useCallback(
    (emoji) => {
      const nativeEmoji = extractNativeEmoji(emoji)
      if (nativeEmoji) {
        onEmojiSelect?.(nativeEmoji)
      }
      setOpen(false)
    },
    [onEmojiSelect],
  )

  return (
    <div ref={wrapRef} className="relative inline-block">
      <button
        type="button"
        disabled={disabled}
        onClick={() => setOpen((v) => !v)}
        aria-label="Open emoji picker"
        aria-expanded={open}
        className={[
          'flex items-center justify-center w-8 h-8 rounded-md',
          'text-white/40 hover:text-white/70 hover:bg-white/[0.07]',
          'transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-500',
          'disabled:opacity-30 disabled:pointer-events-none',
          className,
        ]
          .filter(Boolean)
          .join(' ')}
      >
        😊
      </button>

      {open && (
        <div
          className="absolute bottom-full mb-2 right-0 z-50 shadow-2xl rounded-xl overflow-hidden"
          style={{ filter: 'drop-shadow(0 8px 32px rgba(0,0,0,0.6))' }}
        >
          {pickerData ? (
            <EmojiMartPicker
              data={pickerData}
              onEmojiSelect={handleSelect}
              theme="dark"
              previewPosition="none"
              skinTonePosition="none"
              maxFrequentRows={2}
              perLine={8}
            />
          ) : (
            <div className="flex h-24 w-56 items-center justify-center bg-zinc-900 px-4 text-sm text-zinc-300">
              Loading emojis...
            </div>
          )}
        </div>
      )}
    </div>
  )
}
