'use client'

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

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

  const createEmoji = useCallback(
    async (
      avatarId: string,
      label: string,
      url: string,
      description?: string,
      sortOrder?: number,
      triggerType?: string,
      triggerResult?: 'success' | 'failure',
    ): Promise<Emoji> => {
      setLoading(true)
      setError(null)

      try {
        const data = await relayApiClient.emojis.create(avatarId, {
          label,
          url,
          description,
          trigger_type: triggerType,
          trigger_result: triggerResult,
          sort_order: sortOrder,
        })
        return data.emoji
      } catch (err) {
        const message = err instanceof Error ? err.message : 'Unknown error'
        setError(message)
        throw err
      } finally {
        setLoading(false)
      }
    },
    [relayApiClient],
  )

  const updateEmoji = useCallback(
    async (
      emojiId: string,
      updates: {
        label?: string
        url?: string
        description?: string
        trigger_type?: string
        trigger_result?: 'success' | 'failure' | null
        sort_order?: number
      },
    ): Promise<void> => {
      setLoading(true)
      setError(null)

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

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

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

  const uploadEmojiFile = useCallback(
    async (file: File): Promise<{ url: string; label: string }> => {
      setLoading(true)
      setError(null)

      try {
        const data = await relayApiClient.files.uploadRaw(file)
        const label = file.name.replace(/\.[^.]+$/, '').trim()
        return {
          url: data.data.url,
          label: label || '未命名表情',
        }
      } catch (err) {
        const message = err instanceof Error ? err.message : 'Unknown error'
        setError(message)
        throw err
      } finally {
        setLoading(false)
      }
    },
    [relayApiClient],
  )

  return {
    loading,
    error,
    createEmoji,
    updateEmoji,
    deleteEmoji,
    uploadEmojiFile,
  }
}
