"use client"

import { useState, useCallback } from "react"
import { useAiClient } from "../context/ai-client-provider"
import type { AiChatMessage, AiChatResult } from "../types"

/**
 * AI 聊天 Hook
 *
 * 封装 AI 聊天逻辑，与 UI 分离。
 * 通过 useAiClient() 获取 Server Action 引用。
 */
export function useAiChat(): {
  messages: AiChatMessage[]
  loading: boolean
  error: string | null
  send: (messages: AiChatMessage[], providerId?: string) => Promise<AiChatResult | null>
  clear: () => void
} {
  const aiClient = useAiClient()
  const [messages, setMessages] = useState<AiChatMessage[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const send = useCallback(
    async (input: AiChatMessage[], providerId?: string): Promise<AiChatResult | null> => {
      setLoading(true)
      setError(null)
      try {
        const result = await aiClient.chat({ messages: input, providerId })
        if (result.success && result.data) {
          const assistantContent = result.data.content
          setMessages((prev) => [...prev, ...input, {
            role: "assistant",
            content: assistantContent,
          }])
          return result.data
        }
        setError(result.message ?? "AI request failed")
        return null
      } catch (e) {
        setError(e instanceof Error ? e.message : String(e))
        return null
      } finally {
        setLoading(false)
      }
    },
    [aiClient]
  )

  const clear = useCallback((): void => {
    setMessages([])
    setError(null)
  }, [])

  return { messages, loading, error, send, clear }
}
