'use client'

import { useState, useCallback } from 'react'
import { useAuth } from './useAuth'
import type { AvatarRecord as Avatar, EmojiRecord as Emoji } from '@bowong/auth/client'

export type { Avatar, Emoji }

export interface AvatarWithEmojis extends Avatar {
  emojis: Emoji[]
}

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

  const fetchAvatars = useCallback(async (): Promise<Avatar[]> => {
    setLoading(true)
    setError(null)

    try {
      const data = await relayApiClient.avatars.list()
      return data.avatars
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Unknown error'
      setError(message)
      throw err
    } finally {
      setLoading(false)
    }
  }, [relayApiClient])

  const fetchAvatar = useCallback(
    async (avatarId: string): Promise<AvatarWithEmojis> => {
      setLoading(true)
      setError(null)

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

  const createAvatar = useCallback(
    async (name: string, description?: string): Promise<Avatar> => {
      setLoading(true)
      setError(null)

      try {
        const data = await relayApiClient.avatars.create({ name, description })
        return data.avatar
      } catch (err) {
        const message = err instanceof Error ? err.message : 'Unknown error'
        setError(message)
        throw err
      } finally {
        setLoading(false)
      }
    },
    [relayApiClient],
  )

  const updateAvatar = useCallback(
    async (
      avatarId: string,
      name: string,
      description?: string,
    ): Promise<void> => {
      setLoading(true)
      setError(null)

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

  const deleteAvatar = useCallback(
    async (avatarId: string): Promise<void> => {
      setLoading(true)
      setError(null)

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

  return {
    loading,
    error,
    fetchAvatars,
    fetchAvatar,
    createAvatar,
    updateAvatar,
    deleteAvatar,
  }
}
