'use client'

import { useState, useEffect } from 'react'
import { useAvatars, type Avatar } from '@/hooks/useAvatars'
import { useApiKeyAvatar } from '@/hooks/useApiKeyAvatar'

interface AvatarSelectorProps {
  apikeyId: string
  onClose?: () => void
  onBound?: () => void
}

export function AvatarSelector({ apikeyId, onClose, onBound }: AvatarSelectorProps) {
  const { fetchAvatars } = useAvatars()
  const { bindAvatar, getBoundAvatar } = useApiKeyAvatar()
  const [avatars, setAvatars] = useState<Avatar[]>([])
  const [currentAvatarId, setCurrentAvatarId] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)
  const [binding, setBinding] = useState(false)

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

  const loadData = async () => {
    try {
      setLoading(true)
      const [avatarsList, boundData] = await Promise.all([
        fetchAvatars(),
        getBoundAvatar(apikeyId),
      ])
      setAvatars(avatarsList)
      setCurrentAvatarId(boundData.apikey.avatar_id)
    } catch (err) {
      console.error('Failed to load data:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleSelect = async (avatarId: string | null) => {
    try {
      setBinding(true)
      await bindAvatar(apikeyId, avatarId)
      setCurrentAvatarId(avatarId)
      onBound?.()
      if (onClose) onClose()
    } catch (err) {
      console.error('Failed to bind avatar:', err)
      alert('绑定失败，请重试')
    } finally {
      setBinding(false)
    }
  }

  if (loading) {
    return (
      <div className="rounded-lg border border-slate-200 bg-white p-6 shadow-lg">
        <div className="text-center text-slate-600">加载中...</div>
      </div>
    )
  }

  return (
    <div className="rounded-lg border border-slate-200 bg-white p-6 shadow-lg">
      <div className="mb-4 flex items-center justify-between">
        <h3 className="text-lg font-semibold text-slate-900">选择形象</h3>
        {onClose && (
          <button
            onClick={onClose}
            className="text-slate-400 hover:text-slate-600"
          >
            ✕
          </button>
        )}
      </div>

      {avatars.length === 0 ? (
        <div className="text-center">
          <p className="text-slate-600">还没有创建任何形象</p>
          <a
            href="/avatars"
            className="mt-2 inline-block text-sm text-blue-600 hover:text-blue-700"
          >
            去创建形象 →
          </a>
        </div>
      ) : (
        <div className="space-y-2">
          <button
            onClick={() => handleSelect(null)}
            disabled={binding}
            className={`w-full rounded-lg border px-4 py-3 text-left transition-colors ${
              currentAvatarId === null
                ? 'border-blue-500 bg-blue-50'
                : 'border-slate-200 hover:bg-slate-50'
            } disabled:opacity-50`}
          >
            <div className="font-medium text-slate-900">不使用形象</div>
            <div className="text-sm text-slate-600">不绑定任何表情包</div>
          </button>

          {avatars.map(avatar => (
            <button
              key={avatar.id}
              onClick={() => handleSelect(avatar.id)}
              disabled={binding}
              className={`w-full rounded-lg border px-4 py-3 text-left transition-colors ${
                currentAvatarId === avatar.id
                  ? 'border-blue-500 bg-blue-50'
                  : 'border-slate-200 hover:bg-slate-50'
              } disabled:opacity-50`}
            >
              <div className="font-medium text-slate-900">{avatar.name}</div>
              {avatar.description && (
                <div className="text-sm text-slate-600">{avatar.description}</div>
              )}
            </button>
          ))}
        </div>
      )}

      {binding && (
        <div className="mt-4 text-center text-sm text-slate-600">
          绑定中...
        </div>
      )}
    </div>
  )
}
