'use client'

import { useEffect, useState } from 'react'
import { useRouter, useParams } from 'next/navigation'
import { useAuth } from '@/hooks/useAuth'
import { useAvatars, type AvatarWithEmojis } from '@/hooks/useAvatars'
import { BulkEmojiUpload } from '@/components/BulkEmojiUpload'
import { EmojiList } from '@/components/EmojiList'
import { EmojiForm } from '@/components/EmojiForm'

export default function AvatarDetailPage() {
  const router = useRouter()
  const params = useParams()
  const avatarId = params?.id as string
  const { user, loading: authLoading } = useAuth()
  const { fetchAvatar } = useAvatars()
  const [avatar, setAvatar] = useState<AvatarWithEmojis | null>(null)
  const [loading, setLoading] = useState(true)
  const [showAddForm, setShowAddForm] = useState(false)

  useEffect(() => {
    if (!authLoading && !user) {
      router.replace('/login')
    }
  }, [user, authLoading, router])

  useEffect(() => {
    if (user && avatarId) {
      loadAvatar()
    }
  }, [user, avatarId])

  const loadAvatar = async () => {
    try {
      setLoading(true)
      const data = await fetchAvatar(avatarId)
      setAvatar(data)
    } catch (err) {
      console.error('Failed to load avatar:', err)
      alert('加载失败')
      router.replace('/avatars')
    } finally {
      setLoading(false)
    }
  }

  const handleAddSuccess = () => {
    setShowAddForm(false)
    loadAvatar()
  }

  if (authLoading || !user || loading) {
    return (
      <div className="flex h-screen items-center justify-center">
        <div className="text-slate-600">Loading...</div>
      </div>
    )
  }

  if (!avatar) {
    return null
  }

  return (
    <div className="min-h-screen bg-slate-50">
      <div className="mx-auto max-w-6xl px-4 py-8">
        <div className="mb-6">
          <button
            onClick={() => router.replace('/avatars')}
            className="mb-4 text-sm text-blue-600 hover:text-blue-700"
          >
            ← 返回形象列表
          </button>
          <h1 className="text-3xl font-bold text-slate-900">{avatar.name}</h1>
          {avatar.description && (
            <p className="mt-2 text-slate-600">{avatar.description}</p>
          )}
        </div>

        <div className="mb-6">
          <div className="flex flex-wrap gap-3">
            <button
              onClick={() => setShowAddForm(!showAddForm)}
              className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
            >
              {showAddForm ? '取消添加' : '添加表情'}
            </button>
          </div>
        </div>

        {showAddForm && (
          <div className="mb-6 rounded-lg border border-slate-200 bg-white p-6">
            <h2 className="mb-4 text-lg font-semibold text-slate-900">
              添加新表情
            </h2>
            <EmojiForm
              avatarId={avatarId}
              onSuccess={handleAddSuccess}
              onCancel={() => setShowAddForm(false)}
            />
          </div>
        )}

        <div className="mb-6">
          <BulkEmojiUpload avatarId={avatarId} onSuccess={loadAvatar} />
        </div>

        <EmojiList
          avatarId={avatarId}
          emojis={avatar.emojis}
          onRefresh={loadAvatar}
        />
      </div>
    </div>
  )
}
