'use client'

import { useState } from 'react'
import { useEmojis } from '@/hooks/useEmojis'
import type { Emoji } from '@/hooks/useAvatars'
import type { AvatarEmojiType } from '@/lib/protocol'
import { EmojiMedia } from './EmojiMedia'
import { EmojiForm } from './EmojiForm'

interface EmojiListProps {
  emojis: Emoji[]
  onRefresh: () => void
  avatarId?: string
}

export function EmojiList({ emojis, onRefresh, avatarId = '' }: EmojiListProps) {
  const { deleteEmoji } = useEmojis()
  const [deletingId, setDeletingId] = useState<string | null>(null)
  const [editingId, setEditingId] = useState<string | null>(null)

  const handleDelete = async (emojiId: string) => {
    if (!confirm('确定要删除这个表情吗？')) {
      return
    }

    try {
      setDeletingId(emojiId)
      await deleteEmoji(emojiId)
      onRefresh()
    } catch (err) {
      console.error('Failed to delete emoji:', err)
      alert('删除失败，请重试')
    } finally {
      setDeletingId(null)
    }
  }

  if (emojis.length === 0) {
    return (
      <div className="rounded-lg border border-slate-200 bg-white p-12 text-center">
        <p className="text-slate-600">还没有添加任何表情</p>
        <p className="mt-2 text-sm text-slate-500">
          点击上方按钮添加你的第一个表情
        </p>
      </div>
    )
  }

  return (
    <div className="grid gap-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4">
      {emojis.map(emoji => (
        <div
          key={emoji.id}
          className="group relative rounded-lg border border-slate-200 bg-white p-4 transition-shadow hover:shadow-md"
        >
          <div className="aspect-square overflow-hidden rounded-lg bg-slate-100">
            <EmojiMedia
              url={emoji.url}
              alt={emoji.label}
              className="h-full w-full object-contain"
              fallbackClassName="h-full w-full object-contain"
            />
          </div>
          <div className="mt-3">
            <h3 className="font-medium text-slate-900">{emoji.label}</h3>
            <p className="mt-1 text-xs text-slate-500">
              {emoji.trigger_type}
              {emoji.trigger_result ? ` / ${emoji.trigger_result}` : ''}
            </p>
            {emoji.description && (
              <p className="mt-1 text-sm text-slate-600">{emoji.description}</p>
            )}
          </div>
          <div className="mt-4 flex gap-2">
            <button
              onClick={() => setEditingId(current => current === emoji.id ? null : emoji.id)}
              className="flex-1 rounded-lg border border-slate-300 px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
            >
              {editingId === emoji.id ? '取消编辑' : '编辑'}
            </button>
            <button
              onClick={() => handleDelete(emoji.id)}
              disabled={deletingId === emoji.id}
              className="rounded-lg border border-red-300 px-3 py-2 text-sm font-medium text-red-700 hover:bg-red-50 disabled:opacity-50"
            >
              {deletingId === emoji.id ? '删除中...' : '删除'}
            </button>
          </div>
          {editingId === emoji.id && avatarId && (
            <div className="mt-4 border-t border-slate-200 pt-4">
              <EmojiForm
                avatarId={avatarId}
                emojiId={emoji.id}
                initialLabel={emoji.label}
                initialUrl={emoji.url}
                initialDescription={emoji.description ?? ''}
                initialTriggerType={emoji.trigger_type as AvatarEmojiType}
                initialTriggerResult={emoji.trigger_result ?? ''}
                onSuccess={() => {
                  setEditingId(null)
                  onRefresh()
                }}
                onCancel={() => setEditingId(null)}
              />
            </div>
          )}
        </div>
      ))}
    </div>
  )
}
