import { useState } from 'react';
import { Alert, Button, Card, Input, Modal, Radio, Space, Statistic, Table, Tag, Typography, App } from 'antd';
import { ArrowLeftOutlined, DeleteOutlined, FileTextOutlined, ImportOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { questionAPI } from '../../services/api';
import { questionTypeMap } from '../../utils/validation';
import { getCategoryColorHex } from '../../lib/categoryColors';
import { type ImportMode, type ImportQuestion, parseTextQuestions } from '../../utils/questionTextImport';
import GlassCard from '../../components/common/GlassCard';

const { TextArea } = Input;

const QuestionTextImportPage = () => {
  const navigate = useNavigate();
  const { message } = App.useApp();
  const [rawText, setRawText] = useState('');
  const [mode, setMode] = useState<ImportMode>('incremental');
  const [parseErrors, setParseErrors] = useState<string[]>([]);
  const [questions, setQuestions] = useState<ImportQuestion[]>([]);
  const [loading, setLoading] = useState(false);
  const [tablePagination, setTablePagination] = useState({ current: 1, pageSize: 10, size: 'small' as const });

  const exampleText = [
    '题型|题目类别|分值|题目内容|选项|答案|解析',
    '单选|通用|5|我国首都是哪里?|北京|上海|广州|深圳|A|我国首都为北京',
    '多选|通用|5|以下哪些是水果?|苹果|白菜|香蕉|西红柿|A,C,D|水果包括苹果/香蕉/西红柿',
    '判断|通用|2|地球是圆的||正确|地球接近球体',
    '文字描述|通用|10|请简述你对该岗位的理解||可自由作答|仅用于人工评阅',
  ].join('\n');

  const handleParse = () => {
    const result = parseTextQuestions(rawText);
    setParseErrors(result.errors);
    setQuestions(result.questions);
    setTablePagination((prev) => ({ ...prev, current: 1 }));
    if (result.questions.length === 0) {
      message.error(result.errors.length ? '解析失败，请检查格式' : '未解析到任何题目');
      return;
    }
    if (result.errors.length > 0) {
      message.warning(`解析成功 ${result.questions.length} 条，忽略 ${result.errors.length} 条错误`);
      return;
    }
    message.success(`解析成功 ${result.questions.length} 条`);
  };

  const handleRemove = (idx: number) => {
    setQuestions((prev) => prev.filter((_, i) => i !== idx));
  };

  const indexBase = (tablePagination.current - 1) * tablePagination.pageSize;
  const totalCount = questions.length + parseErrors.length;
  const validCount = questions.length;
  const invalidCount = parseErrors.length;

  const handleImport = async () => {
    if (questions.length === 0) return;
    Modal.confirm({
      title: '确认导入',
      content: mode === 'overwrite' ? '覆盖式导入将清空现有题库并导入当前列表' : '增量导入将按题目内容重复覆盖',
      okText: '开始导入',
      cancelText: '取消',
      onOk: async () => {
        setLoading(true);
        try {
          const res = await questionAPI.importQuestionsFromText({ mode, questions });
          const stats = res.data;
          message.success(`导入完成：新增${stats.inserted}，覆盖${stats.updated}，失败${stats.errors?.length ?? 0}`);
          navigate('/admin/questions');
        } catch (e: any) {
          message.error(e.message || '导入失败');
        } finally {
          setLoading(false);
        }
      },
    });
  };

  const columns = [
    {
      title: '序号',
      key: 'index',
      width: 60,
      render: (_: any, __: any, index: number) => indexBase + index + 1,
    },
    {
      title: '题目内容',
      dataIndex: 'content',
      key: 'content',
      width: 850,
      ellipsis: true,
      onHeaderCell: () => ({ className: 'qt-text-import-th-content' }),
      onCell: () => ({ className: 'qt-text-import-td-content' }),
    },
    {
      title: '题型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: ImportQuestion['type']) => <Tag color="#008C8C">{questionTypeMap[type]}</Tag>,
    },
    {
      title: '题目类别',
      dataIndex: 'category',
      key: 'category',
      width: 120,
      render: (category: string) => {
        const cat = category || '通用';
        return <Tag color={getCategoryColorHex(cat)}>{cat}</Tag>;
      },
    },
    {
      title: '分值',
      dataIndex: 'score',
      key: 'score',
      width: 90,
      render: (score: number) => `${score} 分`,
    },
    {
      title: '答案',
      dataIndex: 'answer',
      key: 'answer',
      width: 160,
      ellipsis: true,
      render: (answer: ImportQuestion['answer']) => (Array.isArray(answer) ? answer.join(' | ') : answer),
    },
    {
      title: '解析',
      dataIndex: 'analysis',
      key: 'analysis',
      width: 320,
      ellipsis: true,
      onHeaderCell: () => ({ className: 'qt-text-import-th-analysis' }),
      onCell: () => ({ className: 'qt-text-import-td-analysis' }),
      render: (analysis: ImportQuestion['analysis']) => (
        <span>
          <Tag color="blue">解析</Tag>
          {analysis || '无'}
        </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      render: (_: any, __: any, index: number) => (
        <Button type="text" danger icon={<DeleteOutlined />} onClick={() => handleRemove(indexBase + index)} />
      ),
    },
  ];

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <Space>
          <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/admin/questions')}>
            返回
          </Button>
          <h1 className="text-2xl font-bold text-white mb-0">
            文本导入题库
          </h1>
        </Space>

        <Space>
          <Radio.Group value={mode} onChange={(e) => setMode(e.target.value)}>
            <Radio.Button value="incremental">增量导入</Radio.Button>
            <Radio.Button value="overwrite">覆盖式导入</Radio.Button>
          </Radio.Group>
          <Button
            type="primary"
            icon={<ImportOutlined />}
            disabled={questions.length === 0}
            loading={loading}
            onClick={handleImport}
          >
            一键导入
          </Button>
        </Space>
      </div>

      <GlassCard className="mb-4">
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          <div className="flex items-center justify-between">
            <Space>
              <Button icon={<FileTextOutlined />} onClick={() => setRawText(exampleText)}>
                填充示例
              </Button>
              <Button type="primary" onClick={handleParse} disabled={!rawText.trim()}>
                解析文本
              </Button>
            </Space>
            <Space size="large">
              <Statistic title={<span className="text-white/70">本次导入题目总数</span>} value={totalCount} valueStyle={{ color: '#1677ff', fontWeight: 700 }} />
              <Statistic title={<span className="text-white/70">有效题目数量</span>} value={validCount} valueStyle={{ color: '#52c41a', fontWeight: 700 }} />
              <Statistic
                title={<span className="text-white/70">无效题目数量</span>}
                value={invalidCount}
                valueStyle={{ color: invalidCount > 0 ? '#ff4d4f' : '#8c8c8c', fontWeight: 700 }}
              />
            </Space>
          </div>

          <TextArea
            value={rawText}
            onChange={(e) => setRawText(e.target.value)}
            placeholder={exampleText}
            rows={12}
            className="bg-white/90"
          />

          {parseErrors.length > 0 && (
            <Alert
              type="warning"
              message="解析错误（已忽略对应行）"
              description={
                <div style={{ maxHeight: 160, overflow: 'auto' }}>
                  {parseErrors.map((err) => (
                    <div key={err}>{err}</div>
                  ))}
                </div>
              }
              showIcon
            />
          )}
        </Space>
      </GlassCard>

      <GlassCard>
        <Table
          columns={columns as any}
          dataSource={questions.map((q, idx) => ({ ...q, key: `${q.content}-${idx}` }))}
          pagination={{ ...tablePagination, showSizeChanger: true }}
          tableLayout="fixed"
          scroll={{ x: 1800 }}
          size="small"
          onChange={(pagination) =>
            setTablePagination({
              current: pagination.current ?? 1,
              pageSize: pagination.pageSize ?? 10,
              size: 'small' as const,
            })
          }
        />
      </GlassCard>
    </div>
  );
};

export default QuestionTextImportPage;

