'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { useAvatars, type Avatar } from '@/hooks/useAvatars'
import { AvatarForm } from './AvatarForm'

interface AvatarManagerProps {
  avatars: Avatar[]
  loading: boolean
  onRefresh: () => void
}

export function AvatarManager({
  avatars,
  loading,
  onRefresh,
}: AvatarManagerProps) {
  const avatarList = Array.isArray(avatars) ? avatars : []
  const router = useRouter()
  const { deleteAvatar } = useAvatars()
  const [showCreateForm, setShowCreateForm] = useState(false)
  const [deletingId, setDeletingId] = useState<string | null>(null)

  const handleDelete = async (avatarId: string) => {
    if (!confirm('确定要删除这个形象吗？所有关联的表情也会被删除。')) {
      return
    }

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

  const handleCreateSuccess = () => {
    setShowCreateForm(false)
    onRefresh()
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-slate-600">加载中...</div>
      </div>
    )
  }

  return (
    <div>
      <div className="mb-6">
        <button
          onClick={() => setShowCreateForm(true)}
          className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
        >
          创建新形象
        </button>
      </div>

      {showCreateForm && (
        <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>
          <AvatarForm
            onSuccess={handleCreateSuccess}
            onCancel={() => setShowCreateForm(false)}
          />
        </div>
      )}

      {avatarList.length === 0 ? (
        <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>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {avatarList.map(avatar => (
            <div
              key={avatar.id}
              className="rounded-lg border border-slate-200 bg-white p-6 transition-shadow hover:shadow-md"
            >
              <h3 className="text-lg font-semibold text-slate-900">
                {avatar.name}
              </h3>
              {avatar.description && (
                <p className="mt-2 text-sm text-slate-600">
                  {avatar.description}
                </p>
              )}
              <div className="mt-4 flex gap-2">
                <button
                  onClick={() => router.push(`/avatars/${avatar.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"
                >
                  管理表情
                </button>
                <button
                  onClick={() => handleDelete(avatar.id)}
                  disabled={deletingId === avatar.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 === avatar.id ? '删除中...' : '删除'}
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
