'use client'

import { useState, useCallback } from 'react'
import { useAuth } from './useAuth'
import type { Avatar, Emoji } from './useAvatars'

export interface ApiKeyAvatar {
  apikey: {
    id: string
    name: string | null
    avatar_id: string | null
  }
  avatar: Avatar | null
  emojis: Emoji[]
}

export function useApiKeyAvatar() {
  const { relayApiClient } = useAuth()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const bindAvatar = useCallback(
    async (apikeyId: string, avatarId: string | null): Promise<void> => {
      setLoading(true)
      setError(null)

      try {
        await relayApiClient.apiKeyAvatars.bind(apikeyId, avatarId)
      } catch (err) {
        const message = err instanceof Error ? err.message : 'Unknown error'
        setError(message)
        throw err
      } finally {
        setLoading(false)
      }
    },
    [relayApiClient],
  )

  const getBoundAvatar = useCallback(
    async (apikeyId: string): Promise<ApiKeyAvatar> => {
      setLoading(true)
      setError(null)

      try {
        const data = await relayApiClient.apiKeyAvatars.get(apikeyId)
        return {
          apikey: data.apikey,
          avatar: data.avatar,
          emojis: data.emojis || [],
        }
      } catch (err) {
        const message = err instanceof Error ? err.message : 'Unknown error'
        setError(message)
        throw err
      } finally {
        setLoading(false)
      }
    },
    [relayApiClient],
  )

  return {
    loading,
    error,
    bindAvatar,
    getBoundAvatar,
  }
}
