import { Alert, Button, Col, Input, Modal, Popconfirm, Row, Segmented, Space, Spin, Typography, message } from 'antd'
import { useEffect, useState } from 'react'
import ReactMarkdown from 'react-markdown'
import AuthenticatedImage from '../components/AuthenticatedImage'
import { wrongQuestionApi } from '../api/client'
import type { WrongQuestion } from '../types'
import { isWrongQuestionProcessing, processingHint } from '../utils/wqProcessing'
import { STATUS_LABELS } from '../types'

interface Props {
  questionId: string
  open: boolean
  onClose: () => void
  onUpdated: () => void
  onDeleted?: () => void
}

export default function WrongQuestionDetail({
  questionId,
  open,
  onClose,
  onUpdated,
  onDeleted,
}: Props) {
  const [wq, setWq] = useState<WrongQuestion | null>(null)
  const [loading, setLoading] = useState(false)
  const [questionText, setQuestionText] = useState('')
  const [approachText, setApproachText] = useState('')
  const [solutionText, setSolutionText] = useState('')
  const [imageMode, setImageMode] = useState<'annotated' | 'original'>('annotated')
  const [saving, setSaving] = useState(false)
  const [regenerating, setRegenerating] = useState(false)
  const [deleting, setDeleting] = useState(false)

  const load = async () => {
    setLoading(true)
    try {
      const { data } = await wrongQuestionApi.get(questionId)
      setWq(data)
      setQuestionText(data.question_text || data.ocr_raw_text || '')
      setApproachText(data.solution_approach || '')
      setSolutionText(data.solution_text || '')
      setImageMode(data.has_annotated_image ? 'annotated' : 'original')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (open && questionId) load()
  }, [open, questionId])

  useEffect(() => {
    if (!open || !wq || !isWrongQuestionProcessing(wq)) return
    const timer = window.setInterval(async () => {
      try {
        const { data } = await wrongQuestionApi.get(questionId)
        setWq(data)
        setQuestionText(data.question_text || data.ocr_raw_text || '')
        setApproachText(data.solution_approach || '')
        setSolutionText(data.solution_text || '')
        if (data.has_annotated_image) setImageMode('annotated')
        if (!isWrongQuestionProcessing(data)) onUpdated()
      } catch {
        /* ignore poll errors */
      }
    }, 4000)
    return () => window.clearInterval(timer)
  }, [open, questionId, wq?.status, wq?.question_text, wq?.error_message])

  const handleSave = async () => {
    setSaving(true)
    try {
      await wrongQuestionApi.update(questionId, {
        question_text: questionText,
        solution_approach: approachText,
        solution_text: solutionText,
      })
      message.success('已保存')
      onUpdated()
    } finally {
      setSaving(false)
    }
  }

  const handleRegenerate = async () => {
    setRegenerating(true)
    try {
      const { data } = await wrongQuestionApi.regenerate(questionId)
      setWq(data)
      setQuestionText(data.question_text || data.ocr_raw_text || '')
      setApproachText(data.solution_approach || '')
      setSolutionText(data.solution_text || '')
      message.success('解题思路已重新生成')
      onUpdated()
    } catch {
      message.error('生成失败，请检查 AI 模型配置')
    } finally {
      setRegenerating(false)
    }
  }

  const handleRetryOcr = async () => {
    await wrongQuestionApi.retryOcr(questionId)
    message.info('已重新识别并标注，请稍后刷新')
    onUpdated()
    onClose()
  }

  const handleDelete = async () => {
    setDeleting(true)
    try {
      await wrongQuestionApi.remove(questionId)
      message.success('已删除')
      onDeleted?.()
      onClose()
    } catch {
      message.error('删除失败')
    } finally {
      setDeleting(false)
    }
  }

  return (
    <Modal
      title={
        wq
          ? `${wq.subject_name}${wq.category === 'olympiad' ? ' · 奥数' : ''} · 详情`
          : '详情'
      }
      open={open}
      onCancel={onClose}
      width="90%"
      style={{ maxWidth: 960 }}
      footer={
        <Space wrap>
          <Popconfirm title="确定删除该题？" onConfirm={handleDelete}>
            <Button danger loading={deleting}>
              删除
            </Button>
          </Popconfirm>
          <Button onClick={handleRetryOcr}>重新识别标注</Button>
          <Button loading={regenerating} onClick={handleRegenerate}>
            重新生成思路
          </Button>
          <Button type="primary" loading={saving} onClick={handleSave}>
            保存编辑
          </Button>
        </Space>
      }
    >
      <Spin spinning={loading}>
        {wq && (
          <>
            <Space wrap style={{ marginBottom: 8 }}>
              <Typography.Text type="secondary">状态：{STATUS_LABELS[wq.status]}</Typography.Text>
              {wq.has_annotated_image && !wq.error_message && (
                <Typography.Text type="danger">红色框为自动标注的错误位置</Typography.Text>
              )}
            </Space>
            {wq.error_message && (
              <Alert
                message="处理失败"
                description={wq.error_message}
                type="error"
                showIcon
                style={{ marginBottom: 12 }}
              />
            )}
            {wq.status === 'pending' && !wq.error_message && (
              <Alert message={processingHint(wq)} type="info" showIcon style={{ marginBottom: 12 }} />
            )}
            {wq.status === 'ocr_done' && !wq.question_text && !wq.error_message && (
              <Alert message={processingHint(wq)} type="info" showIcon style={{ marginBottom: 12 }} />
            )}
            {(wq.solution_approach || wq.solution_text) && (
              <Alert
                message="AI 识别与标注，请核对后再使用"
                type="warning"
                showIcon
                style={{ margin: '12px 0' }}
              />
            )}
            <Row gutter={16} style={{ marginTop: 12 }}>
              <Col xs={24} md={10}>
                {wq.has_annotated_image && (
                  <Segmented
                    block
                    style={{ marginBottom: 8 }}
                    value={imageMode}
                    onChange={(v) => setImageMode(v as 'annotated' | 'original')}
                    options={[
                      { label: '标注图', value: 'annotated' },
                      { label: '原图', value: 'original' },
                    ]}
                  />
                )}
                <AuthenticatedImage
                  questionId={wq.id}
                  variant={imageMode}
                  alt="原题"
                  style={{ width: '100%', borderRadius: 8, border: '1px solid #f0f0f0' }}
                />
                {wq.ocr_raw_text && (
                  <div style={{ marginTop: 12 }}>
                    <Typography.Text strong>OCR 原文（已排除手写作答）</Typography.Text>
                    <pre
                      style={{
                        background: '#fafafa',
                        padding: 8,
                        fontSize: 12,
                        maxHeight: 150,
                        overflow: 'auto',
                        whiteSpace: 'pre-wrap',
                      }}
                    >
                      {wq.ocr_raw_text}
                    </pre>
                  </div>
                )}
              </Col>
              <Col xs={24} md={14}>
                <Typography.Text strong>识别题目（可编辑）</Typography.Text>
                <Input.TextArea
                  rows={5}
                  value={questionText}
                  onChange={(e) => setQuestionText(e.target.value)}
                  style={{ marginTop: 8, marginBottom: 16 }}
                />
                <Typography.Text strong>解题思路</Typography.Text>
                <Input.TextArea
                  rows={4}
                  value={approachText}
                  onChange={(e) => setApproachText(e.target.value)}
                  placeholder="识别完成后自动生成，类似作业帮「解题思路」"
                  style={{ marginTop: 8, marginBottom: 16 }}
                />
                {approachText && (
                  <div
                    style={{
                      background: '#e6f4ff',
                      padding: 12,
                      borderRadius: 8,
                      marginBottom: 16,
                      border: '1px solid #91caff',
                    }}
                  >
                    <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                      思路预览
                    </Typography.Text>
                    <ReactMarkdown>{approachText}</ReactMarkdown>
                  </div>
                )}
                <Typography.Text strong>详细解答</Typography.Text>
                <Input.TextArea
                  rows={8}
                  value={solutionText}
                  onChange={(e) => setSolutionText(e.target.value)}
                  style={{ marginTop: 8, marginBottom: 12 }}
                />
                {solutionText && (
                  <div style={{ background: '#fafafa', padding: 12, borderRadius: 8 }}>
                    <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                      解答预览
                    </Typography.Text>
                    <ReactMarkdown>{solutionText}</ReactMarkdown>
                  </div>
                )}
              </Col>
            </Row>
          </>
        )}
      </Spin>
    </Modal>
  )
}
