import { Alert, Button, Spin, Typography } from 'antd'
import { useCallback, useEffect, useState } from 'react'
import ReactMarkdown from 'react-markdown'
import { examApi, settingsApi } from '../api/client'

interface Props {
  studentId: string
  subjectName: string | null
}

function apiErrorMessage(err: unknown, fallback: string): string {
  if (err && typeof err === 'object' && 'response' in err) {
    const detail = (err as { response?: { data?: { detail?: unknown } } }).response?.data?.detail
    if (typeof detail === 'string') return detail
  }
  return fallback
}

export default function ReviewAiInsight({ studentId, subjectName }: Props) {
  const [enabled, setEnabled] = useState(true)
  const [insight, setInsight] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    settingsApi.appFeatures().then(({ data }) => setEnabled(data.ai_review_enabled)).catch(() => {})
  }, [])

  const loadInsight = useCallback(async () => {
    if (!subjectName || !enabled) {
      setInsight(null)
      setError(null)
      return
    }
    setLoading(true)
    setError(null)
    try {
      const { data } = await examApi.reviewInsight(studentId, subjectName)
      setInsight(data.insight)
    } catch (err) {
      setError(apiErrorMessage(err, 'AI 解读生成失败，请检查模型配置'))
      setInsight(null)
    } finally {
      setLoading(false)
    }
  }, [studentId, subjectName, enabled])

  useEffect(() => {
    loadInsight()
  }, [loadInsight])

  if (!subjectName) return null

  if (!enabled) {
    return (
      <Alert
        style={{ marginTop: 20 }}
        type="info"
        showIcon
        message="AI 复盘解读已在系统设置中关闭"
      />
    )
  }

  return (
    <div style={{ marginTop: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
        <Typography.Text strong style={{ fontSize: 15 }}>
          AI 解读与建议 · {subjectName}
        </Typography.Text>
        <Button size="small" loading={loading} onClick={loadInsight}>
          重新生成
        </Button>
      </div>
      {loading && !insight && (
        <div style={{ textAlign: 'center', padding: 24 }}>
          <Spin tip="AI 正在分析复盘数据…" />
        </div>
      )}
      {error && <Alert type="error" message={error} showIcon style={{ marginBottom: 12 }} />}
      {insight && (
        <div
          style={{
            background: '#f6ffed',
            border: '1px solid #b7eb8f',
            borderRadius: 8,
            padding: 16,
          }}
        >
          <ReactMarkdown>{insight}</ReactMarkdown>
        </div>
      )}
    </div>
  )
}
