import { DeleteOutlined } from '@ant-design/icons'
import { Button, Popconfirm, Space, Tag, Typography, message } from 'antd'
import { useEffect } from 'react'
import { wrongQuestionApi } from '../api/client'
import type { WrongQuestion } from '../types'
import { isWrongQuestionProcessing, processingHint } from '../utils/wqProcessing'
import { STATUS_LABELS } from '../types'
import AuthenticatedImage from './AuthenticatedImage'
import WrongQuestionDetail from '../pages/WrongQuestionDetail'

interface Props {
  items: WrongQuestion[]
  selectedId: string | null
  onSelect: (id: string | null) => void
  onRefresh: () => void
  emptyText?: string
  pollWhenProcessing?: boolean
}

function cardSummary(wq: WrongQuestion): { tone: 'error' | 'pending' | 'normal'; text: string } {
  if (wq.error_message) {
    return { tone: 'error', text: wq.error_message }
  }
  if (isWrongQuestionProcessing(wq)) {
    return { tone: 'pending', text: processingHint(wq) }
  }
  return {
    tone: 'normal',
    text: wq.question_text || wq.ocr_raw_text || STATUS_LABELS[wq.status],
  }
}

export default function WrongQuestionList({
  items,
  selectedId,
  onSelect,
  onRefresh,
  emptyText = '暂无记录',
  pollWhenProcessing = true,
}: Props) {
  const hasProcessing = pollWhenProcessing && items.some(isWrongQuestionProcessing)

  useEffect(() => {
    if (!hasProcessing) return
    const timer = window.setInterval(() => onRefresh(), 4000)
    return () => window.clearInterval(timer)
  }, [hasProcessing, onRefresh])

  const handleDelete = async (id: string) => {
    try {
      await wrongQuestionApi.remove(id)
      message.success('已删除')
      if (selectedId === id) onSelect(null)
      onRefresh()
    } catch {
      message.error('删除失败')
    }
  }

  return (
    <>
      <div className="wq-grid">
        {items.map((wq) => {
          const summary = cardSummary(wq)
          return (
            <div key={wq.id} className="wq-card">
              <div className="wq-card-click" onClick={() => onSelect(wq.id)}>
                <AuthenticatedImage questionId={wq.id} variant="annotated" alt="题目" className="wq-card-img" />
                <div className="wq-card-body">
                  <Space size={4} wrap>
                    <Typography.Text strong>{wq.subject_name}</Typography.Text>
                    {wq.category === 'olympiad' && <Tag color="gold">奥数</Tag>}
                    <Tag color={wq.error_message || wq.status === 'failed' ? 'error' : isWrongQuestionProcessing(wq) ? 'processing' : 'default'}>
                      {wq.error_message ? '失败' : STATUS_LABELS[wq.status]}
                    </Tag>
                  </Space>
                  <Typography.Paragraph
                    ellipsis={{ rows: 3 }}
                    style={{
                      margin: '8px 0 0',
                      fontSize: 13,
                      color: summary.tone === 'error' ? '#ff4d4f' : summary.tone === 'pending' ? '#1677ff' : undefined,
                    }}
                  >
                    {summary.text}
                  </Typography.Paragraph>
                </div>
              </div>
              <div className="wq-card-actions">
                <Popconfirm title="确定删除该题？" onConfirm={() => handleDelete(wq.id)}>
                  <Button
                    type="text"
                    danger
                    size="small"
                    icon={<DeleteOutlined />}
                    onClick={(e) => e.stopPropagation()}
                  >
                    删除
                  </Button>
                </Popconfirm>
              </div>
            </div>
          )
        })}
      </div>
      {items.length === 0 && <Typography.Text type="secondary">{emptyText}</Typography.Text>}
      {selectedId && (
        <WrongQuestionDetail
          questionId={selectedId}
          open={!!selectedId}
          onClose={() => onSelect(null)}
          onUpdated={onRefresh}
          onDeleted={() => {
            onSelect(null)
            onRefresh()
          }}
        />
      )}
    </>
  )
}
