'use client'

import { useState, useEffect } from 'react'
import { useApiKeyAvatar, type ApiKeyAvatar } from '@/hooks/useApiKeyAvatar'
import { EmojiMedia } from './EmojiMedia'

interface EmojiPickerProps {
  apikeyId: string
  onSelect: (emoji: string) => void
  onClose: () => void
}

export function EmojiPicker({ apikeyId, onSelect, onClose }: EmojiPickerProps) {
  const { getBoundAvatar } = useApiKeyAvatar()
  const [data, setData] = useState<ApiKeyAvatar | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    loadEmojis()
  }, [apikeyId])

  const loadEmojis = async () => {
    try {
      setLoading(true)
      const result = await getBoundAvatar(apikeyId)
      setData(result)
    } catch (err) {
      console.error('Failed to load emojis:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleSelect = (url: string) => {
    onSelect(url)
    onClose()
  }

  if (loading) {
    return (
      <div className="absolute bottom-full left-0 mb-2 w-80 rounded-lg border border-slate-200 bg-white p-4 shadow-lg">
        <div className="text-center text-sm text-slate-600">加载中...</div>
      </div>
    )
  }

  if (!data?.avatar || data.emojis.length === 0) {
    return (
      <div className="absolute bottom-full left-0 mb-2 w-80 rounded-lg border border-slate-200 bg-white p-4 shadow-lg">
        <div className="mb-2 flex items-center justify-between">
          <h3 className="font-semibold text-slate-900">表情</h3>
          <button
            onClick={onClose}
            className="text-slate-400 hover:text-slate-600"
          >
            ✕
          </button>
        </div>
        <div className="text-center">
          <p className="text-sm text-slate-600">
            {!data?.avatar ? '未绑定形象' : '该形象还没有表情'}
          </p>
          <a
            href="/avatars"
            className="mt-2 inline-block text-sm text-blue-600 hover:text-blue-700"
          >
            去管理形象 →
          </a>
        </div>
      </div>
    )
  }

  return (
    <div className="absolute bottom-full left-0 mb-2 w-80 rounded-lg border border-slate-200 bg-white p-4 shadow-lg">
      <div className="mb-3 flex items-center justify-between">
        <h3 className="font-semibold text-slate-900">{data.avatar.name}</h3>
        <button
          onClick={onClose}
          className="text-slate-400 hover:text-slate-600"
        >
          ✕
        </button>
      </div>

      <div className="grid max-h-64 grid-cols-4 gap-2 overflow-y-auto">
        {data.emojis.map(emoji => (
          <button
            key={emoji.id}
            onClick={() => handleSelect(emoji.url)}
            className="group relative aspect-square overflow-hidden rounded-lg border border-slate-200 bg-slate-50 p-2 transition-all hover:border-blue-500 hover:shadow-md"
            title={emoji.label}
          >
            <EmojiMedia
              url={emoji.url}
              alt={emoji.label}
              className="h-full w-full object-contain"
              fallbackClassName="h-full w-full object-contain"
            />
            <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/60 to-transparent px-1 py-0.5 text-xs text-white opacity-0 transition-opacity group-hover:opacity-100">
              {emoji.label}
            </div>
          </button>
        ))}
      </div>
    </div>
  )
}
