'use client'

import { Smile } from 'lucide-react'
import dynamic from 'next/dynamic'
import { useState, useRef, useEffect } from 'react'

import { Button } from '@/components/ui/button'

// Динамически импортируем EmojiPicker чтобы избежать проблем с SSR
const EmojiPicker = dynamic(() => import('emoji-picker-react'), { ssr: false })

interface EmojiPickerComponentProps {
  onEmojiSelect: (emoji: string) => void
}

export function EmojiPickerComponent({ onEmojiSelect }: EmojiPickerComponentProps) {
  const [showPicker, setShowPicker] = useState(false)
  const pickerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (pickerRef.current && !pickerRef.current.contains(event.target as Node)) {
        setShowPicker(false)
      }
    }

    if (showPicker) {
      document.addEventListener('mousedown', handleClickOutside)
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [showPicker])

  const handleEmojiClick = (emojiData: { emoji: string }) => {
    onEmojiSelect(emojiData.emoji)
    setShowPicker(false)
  }

  return (
    <div className="relative" ref={pickerRef}>
      <Button
        type="button"
        variant="ghost"
        onClick={() => setShowPicker(!showPicker)}
        className="text-white/60 hover:text-white hover:bg-white/10 h-10 w-10 p-0"
      >
        <Smile className="h-4 w-4" />
      </Button>

      {showPicker && (
        <div className="absolute bottom-full right-0 mb-2 z-50">
          <div className="bg-gray-800 border border-white/20 rounded-lg overflow-hidden shadow-xl">
            <EmojiPicker onEmojiClick={handleEmojiClick} width={350} height={400} />
          </div>
        </div>
      )}
    </div>
  )
}
