'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useAuth } from '@/hooks/useAuth'
import { useAvatars, type Avatar } from '@/hooks/useAvatars'
import { AvatarManager } from '@/components/AvatarManager'

export default function AvatarsPage() {
  const router = useRouter()
  const { user, loading: authLoading } = useAuth()
  const { fetchAvatars } = useAvatars()
  const [avatars, setAvatars] = useState<Avatar[]>([])
  const [loading, setLoading] = useState(true)

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

  useEffect(() => {
    if (user) {
      loadAvatars()
    }
  }, [user])

  const loadAvatars = async () => {
    try {
      setLoading(true)
      const data = await fetchAvatars()
      setAvatars(Array.isArray(data) ? data : [])
    } catch (err) {
      console.error('Failed to load avatars:', err)
      setAvatars([])
    } finally {
      setLoading(false)
    }
  }

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

  return (
    <div className="min-h-screen bg-slate-50">
      <div className="mx-auto max-w-6xl px-4 py-8">
        <div className="mb-6">
          <h1 className="text-3xl font-bold text-slate-900">形象管理</h1>
          <p className="mt-2 text-slate-600">
            管理你的龙虾形象和表情包
          </p>
        </div>

        <AvatarManager
          avatars={avatars}
          loading={loading}
          onRefresh={loadAvatars}
        />
      </div>
    </div>
  )
}
