"use client"

import { useState, useCallback } from "react"
import { useAiClient } from "../context/ai-client-provider"
import type {
  SimilarQuestionInput,
  SimilarQuestionResult,
  GradingInput,
  GradingSuggestion,
} from "../types"

/**
 * AI 建议 Hook
 *
 * 封装 AI 建议调用逻辑（相似题、批改建议等），与 UI 分离。
 */
export function useAiSuggestion(): {
  loading: boolean
  error: string | null
  suggestSimilarQuestions: (
    input: SimilarQuestionInput
  ) => Promise<SimilarQuestionResult[] | null>
  suggestGrading: (input: GradingInput) => Promise<GradingSuggestion | null>
} {
  const aiClient = useAiClient()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const suggestSimilarQuestions = useCallback(
    async (input: SimilarQuestionInput): Promise<SimilarQuestionResult[] | null> => {
      setLoading(true)
      setError(null)
      try {
        const result = await aiClient.suggestSimilarQuestions(input)
        if (result.success && result.data) {
          return result.data
        }
        setError(result.message ?? "AI suggestion failed")
        return null
      } catch (e) {
        setError(e instanceof Error ? e.message : String(e))
        return null
      } finally {
        setLoading(false)
      }
    },
    [aiClient]
  )

  const suggestGrading = useCallback(
    async (input: GradingInput): Promise<GradingSuggestion | null> => {
      setLoading(true)
      setError(null)
      try {
        const result = await aiClient.suggestGrading(input)
        if (result.success && result.data) {
          return result.data
        }
        setError(result.message ?? "AI grading failed")
        return null
      } catch (e) {
        setError(e instanceof Error ? e.message : String(e))
        return null
      } finally {
        setLoading(false)
      }
    },
    [aiClient]
  )

  return { loading, error, suggestSimilarQuestions, suggestGrading }
}
