import { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Space, 
  Modal, 
  Form, 
  Input, 
  Select, 
  Upload, 
  App, 
  Tag,
  Popconfirm,
  Row,
  Col,
  InputNumber,
  Radio,
  Checkbox,
  DatePicker
} from 'antd';
import dayjs from 'dayjs';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  UploadOutlined,
  DownloadOutlined,
  SearchOutlined,
  ReloadOutlined,
  FileTextOutlined
} from '@ant-design/icons';
import * as XLSX from 'xlsx';
import { useNavigate } from 'react-router-dom';
import { questionAPI } from '../../services/api';
import { formatDate, questionTypeMap, questionTypeColors } from '../../utils/validation';
import { getCategoryColorHex } from '../../lib/categoryColors';
import GlassCard from '../../components/common/GlassCard';

const { Option } = Select;
const { TextArea } = Input;

interface Question {
  id: string;
  content: string;
  type: 'single' | 'multiple' | 'judgment' | 'text';
  options?: string[];
  answer: string | string[];
  analysis?: string;
  score: number;
  createdAt: string;
}

const QuestionManagePage = () => {
  const navigate = useNavigate();
  const { message } = App.useApp();
  const [questions, setQuestions] = useState<Question[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingQuestion, setEditingQuestion] = useState<Question | null>(null);
  const [form] = Form.useForm();
  // 筛选条件
  const [searchType, setSearchType] = useState<string>('');
  const [searchCategory, setSearchCategory] = useState<string>('');
  const [searchKeyword, setSearchKeyword] = useState<string>('');
  const [searchDateRange, setSearchDateRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null] | null>(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    size: 'small' as const,
  });
  // 动态选项
  const [availableTypes, setAvailableTypes] = useState<string[]>([]);
  const [availableCategories, setAvailableCategories] = useState<string[]>([]);

  useEffect(() => {
    fetchQuestions();
  }, [pagination.current, pagination.pageSize, searchType, searchCategory, searchKeyword, searchDateRange]);

  const fetchQuestions = async () => {
    try {
      setLoading(true);
      const response = await questionAPI.getQuestions({
        type: searchType,
        category: searchCategory,
        keyword: searchKeyword,
        startDate: searchDateRange?.[0]?.format('YYYY-MM-DD'),
        endDate: searchDateRange?.[1]?.format('YYYY-MM-DD'),
        page: pagination.current,
        limit: pagination.pageSize
      });
      
      setQuestions(response.data);
      setPagination(prev => ({
        ...prev,
        total: (response as any).pagination?.total || response.data.length
      }));
      
      // 提取并更新可用的题型和类别列表
      const allQuestionsRes = await questionAPI.getQuestions({ limit: 10000 });
      const allList = ((allQuestionsRes as any).data as any[]) || [];
      const types = [...new Set(allList.map((q: any) => String(q.type)))];
      const categories = [...new Set(allList.map((q: any) => String(q.category || '通用')))];
      setAvailableTypes(types);
      setAvailableCategories(categories);
    } catch (error: any) {
      message.error(error.message || '获取题目列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setEditingQuestion(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (question: Question) => {
    const normalizeJudgmentAnswer = (raw: unknown) => {
      const v = String(raw ?? '').trim();
      if (['A', 'T', 'true', 'True', 'TRUE', '1', '正确', '对', '是'].includes(v)) return '正确';
      if (['B', 'F', 'false', 'False', 'FALSE', '0', '错误', '错', '否', '不是'].includes(v)) return '错误';
      return v;
    };

    setEditingQuestion(question);
    form.setFieldsValue({
      ...question,
      options: question.options?.join('\n'),
      analysis: question.analysis || '',
      answer: question.type === 'judgment' ? normalizeJudgmentAnswer(question.answer) : question.answer,
    });
    setModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      await questionAPI.deleteQuestion(id);
      message.success('删除成功');
      fetchQuestions();
    } catch (error: any) {
      message.error(error.message || '删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      const normalizeJudgmentAnswer = (raw: unknown) => {
        const v = String(raw ?? '').trim();
        if (['A', 'T', 'true', 'True', 'TRUE', '1', '正确', '对', '是'].includes(v)) return '正确';
        if (['B', 'F', 'false', 'False', 'FALSE', '0', '错误', '错', '否', '不是'].includes(v)) return '错误';
        return v;
      };

      const formData = {
        ...values,
        options: values.options ? values.options.split('\n').filter((opt: string) => opt.trim()) : undefined,
        answer: values.type === 'judgment' ? normalizeJudgmentAnswer(values.answer) : values.answer,
      };

      if (editingQuestion) {
        await questionAPI.updateQuestion(editingQuestion.id, formData);
        message.success('更新成功');
      } else {
        await questionAPI.createQuestion(formData);
        message.success('创建成功');
      }
      
      setModalVisible(false);
      fetchQuestions();
    } catch (error: any) {
      message.error(error.message || '操作失败');
    }
  };

  // 导入题目
  const handleImport = async (file: File) => {
    try {
      // 创建一个 FileReader 来读取 Excel 文件
      const reader = new FileReader();
      reader.onload = async (e) => {
        try {
          const data = new Uint8Array(e.target?.result as ArrayBuffer);
          // 使用顶部导入的 XLSX 对象，避免动态导入的问题
          const workbook = XLSX.read(data, { type: 'array' });
          const sheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[sheetName];
          
          // 转换为 JSON 数据
          const rawData = XLSX.utils.sheet_to_json(worksheet);
          
          // 解析数据
          const questions = rawData.map((row: any) => ({
            content: row['题目内容'] || row['content'],
            type: row['题型'] || row['type'],
            category: row['题目类别'] || row['category'] || '通用',
            answer: row['标准答案'] || row['answer'],
            score: parseInt(row['分值'] || row['score']) || 0,
            options: row['选项'] || row['options']
          }));
          
          // 检查重复题目
          const existingQuestions = await Promise.all(
            questions.map(async (q: any) => {
              try {
                // 获取所有题目，然后在前端检查重复
                const response = await questionAPI.getQuestions({ limit: 10000 });
                const found = response.data.find((existing: any) => existing.content === q.content);
                return { ...q, existing: found };
              } catch (error) {
                return { ...q, existing: null };
              }
            })
          );
          
          // 分离已存在和不存在的题目
          const existing = existingQuestions.filter(q => q.existing);
          const newQuestions = existingQuestions.filter(q => !q.existing);
          
          // 如果没有重复题目，直接导入
          if (existing.length === 0) {
            await importQuestions(existingQuestions);
            return;
          }
          
          // 如果有重复题目，弹出确认框
          const modal = Modal.confirm({
            title: '导入确认',
            content: (
              <div>
                <p>发现 {existing.length} 道题目已存在，{newQuestions.length} 道新题目</p>
                <p>请选择处理方式：</p>
                <Radio.Group defaultValue="skip">
                  <Radio value="skip">跳过已存在的题目</Radio>
                  <Radio value="overwrite">覆盖已存在的题目</Radio>
                  <Radio value="cancel">放弃导入</Radio>
                </Radio.Group>
                <Checkbox defaultChecked={false} id="applyAll">
                  应用本次导入所有题目
                </Checkbox>
              </div>
            ),
            onOk: async () => {
              try {
                const checkbox = document.getElementById('applyAll') as HTMLInputElement;
                const applyAll = checkbox?.checked || false;
                const radios = document.querySelectorAll('input[type="radio"]');
                let option = 'skip';
                radios.forEach(radio => {
                  if ((radio as HTMLInputElement).checked) {
                    option = (radio as HTMLInputElement).value;
                  }
                });
                
                if (option === 'cancel') {
                  message.info('已取消导入');
                  return;
                }
                
                let questionsToImport = existingQuestions;
                if (option === 'skip') {
                  questionsToImport = newQuestions;
                }
                
                await importQuestions(questionsToImport);
                modal.destroy(); // 关闭弹窗
              } catch (error) {
                modal.destroy(); // 关闭弹窗
              }
            },
            onCancel: () => {
              message.info('已取消导入');
            }
          });
        } catch (error: any) {
          console.error('导入失败:', error);
          message.error(error.message || '导入失败');
        }
      };
      
      reader.readAsArrayBuffer(file);
    } catch (error: any) {
      message.error(error.message || '导入失败');
    }
    return false; // 阻止上传
  };
  
  // 实际导入题目
  const importQuestions = async (questions: any[]) => {
    try {
      // 将题目数据转换为 FormData
      const formData = new FormData();
      
      // 创建一个新的 Excel 文件
      // 使用顶部导入的 XLSX 对象，避免动态导入的问题
      const workbook = XLSX.utils.book_new();
      const worksheet = XLSX.utils.json_to_sheet(questions);
      XLSX.utils.book_append_sheet(workbook, worksheet, '题目列表');
      
      // 将 workbook 转换为 blob
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const file = new File([blob], 'temp_import.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      formData.append('file', file);
      
      // 调用导入 API
      const response = await questionAPI.importQuestions(file);
      message.success(`成功导入 ${response.data.imported} 道题`);
      if (response.data.errors.length > 0) {
        message.warning(`有 ${response.data.errors.length} 道题导入失败`);
      }
      fetchQuestions();
    } catch (error: any) {
      message.error(error.message || '导入失败');
      console.error('导入失败:', error);
    }
  };

  // 导出题目为Excel
  const handleExport = async () => {
    try {
      setLoading(true);
      
      // 使用现有的API获取题目数据
      let exportUrl = '/api/admin/export/questions';
      if (searchType) {
        exportUrl += `?type=${encodeURIComponent(searchType)}`;
      }
      
      // 获取题目数据
      const response = await fetch(exportUrl, {
        method: 'GET',
        headers: {
          'Authorization': localStorage.getItem('survey_admin') ? `Bearer ${JSON.parse(localStorage.getItem('survey_admin') || '{}').token}` : '',
          'Content-Type': 'application/json',
        },
        credentials: 'include',
      });
      
      if (!response.ok) {
        throw new Error('导出失败');
      }
      
      // 获取JSON数据
      const result = await response.json();
      
      // 检查结果格式
      if (!result || !result.success || !result.data) {
        throw new Error('导出失败：数据格式错误');
      }
      
      const questionsData = result.data;
      
      // 创建工作簿和工作表
      const workbook = XLSX.utils.book_new();
      const worksheet = XLSX.utils.json_to_sheet(questionsData);
      
      // 设置列宽
      const columnWidths = [
        { wch: 10 }, // ID
        { wch: 60 }, // 题目内容
        { wch: 10 }, // 题型
        { wch: 15 }, // 题目类别
        { wch: 80 }, // 选项
        { wch: 20 }, // 标准答案
        { wch: 8 },  // 分值
        { wch: 20 }  // 创建时间
      ];
      worksheet['!cols'] = columnWidths;
      
      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(workbook, worksheet, '题目列表');
      
      // 生成Excel文件
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `题库导出_${new Date().getTime()}.xlsx`);
      document.body.appendChild(link);
      link.click();
      
      // 清理
      window.URL.revokeObjectURL(url);
      document.body.removeChild(link);
      
      message.success('导出成功');
    } catch (error: any) {
      console.error('导出失败:', error);
      message.error(error.message || '导出失败');
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '序号',
      key: 'index',
      width: 60,
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '题目内容',
      dataIndex: 'content',
      key: 'content',
      width: '30%',
      ellipsis: true,
    },
    {
      title: '题型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => (
        <Tag color={questionTypeColors[type as keyof typeof questionTypeColors]}>
          {questionTypeMap[type as keyof typeof questionTypeMap]}
        </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: 80,
      render: (score: number) => <span className="font-semibold">{score} 分</span>,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 160,
      render: (date: string) => formatDate(date),
    },
    {
      title: <div style={{ textAlign: 'center' }}>操作</div>,
      key: 'action',
      width: 120,
      render: (_: any, record: Question) => (
        <Space size="small">
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            size="small"
          />
          <Popconfirm
            title="确定删除这道题吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="text"
              danger
              icon={<DeleteOutlined />}
              size="small"
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <GlassCard>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-white mb-4">题库管理</h1>
        
        <div className="flex flex-wrap gap-4 items-center">
          {/* 题型筛选 - 动态生成选项 */}
          <Select
            placeholder="筛选题型"
            allowClear
            style={{ width: 120 }}
            value={searchType}
            onChange={setSearchType}
          >
            <Option value="">全部</Option>
            {availableTypes.map(type => (
              <Option key={type} value={type}>
                {questionTypeMap[type as keyof typeof questionTypeMap] || type}
              </Option>
            ))}
          </Select>
          
          {/* 题目类别筛选 - 动态生成选项 */}
          <Select
            placeholder="筛选类别"
            allowClear
            style={{ width: 120 }}
            value={searchCategory}
            onChange={setSearchCategory}
          >
            <Option value="">全部</Option>
            {availableCategories.map(category => (
              <Option key={category} value={category}>
                {category}
              </Option>
            ))}
          </Select>
          
          {/* 创建时间筛选 */}
          <DatePicker.RangePicker
            placeholder={['开始时间', '结束时间']}
            value={searchDateRange}
            onChange={setSearchDateRange}
            format="YYYY-MM-DD"
          />
          
          {/* 关键字搜索 */}
          <Input
            placeholder="关键字搜索"
            style={{ width: 200 }}
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            onPressEnter={fetchQuestions}
          />
          
          {/* 刷新按钮 */}
          <Button icon={<ReloadOutlined />} onClick={fetchQuestions}>
            刷新
          </Button>
          
          {/* 导入导出按钮 */}
          <Space>
            <Upload
              accept=".xlsx,.xls"
              showUploadList={false}
              beforeUpload={handleImport}
            >
              <Button icon={<DownloadOutlined />}>Excel导入</Button>
            </Upload>
            <Button icon={<FileTextOutlined />} onClick={() => navigate('/admin/questions/text-import')}>
              文本导入
            </Button>
            <Button icon={<UploadOutlined />} onClick={handleExport}>
              Excel导出
            </Button>
          </Space>
          
          {/* 新增题目按钮 */}
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增题目
          </Button>
        </div>
      </div>

      <Table
        columns={columns}
        dataSource={questions}
        rowKey="id"
        size="small"
        loading={loading}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
        }}
        onChange={(newPagination) => setPagination(newPagination as any)}
      />

      {/* 编辑/新增模态框 */}
      <Modal
        title={editingQuestion ? '编辑题目' : '新增题目'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{ score: 10 }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="type"
                label="题型"
                rules={[{ required: true, message: '请选择题型' }]}
              >
                <Select placeholder="选择题型">
                  <Option value="single">单选题</Option>
                  <Option value="multiple">多选题</Option>
                  <Option value="judgment">判断题</Option>
                  <Option value="text">文字描述题</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="score"
                label="分值"
                rules={[{ required: true, message: '请输入分值' }]}
              >
                <InputNumber min={0} max={100} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="content"
            label="题目内容"
            rules={[{ required: true, message: '请输入题目内容' }]}
          >
            <TextArea rows={3} placeholder="请输入题目内容" />
          </Form.Item>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}
          >
            {({ getFieldValue }) => {
              const type = getFieldValue('type');
              if (type === 'single' || type === 'multiple') {
                return (
                  <Form.Item
                    name="options"
                    label="选项（每行一个）"
                    rules={[{ required: true, message: '请输入选项' }]}
                  >
                    <TextArea
                      rows={6}
                      placeholder="请输入选项，每行一个，例如：\n选项A\n选项B\n选项C\n选项D"
                    />
                  </Form.Item>
                );
              }
              return null;
            }}
          </Form.Item>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.type !== currentValues.type || prevValues.score !== currentValues.score
            }
          >
            {({ getFieldValue }) => {
              const type = getFieldValue('type');
              const score = Number(getFieldValue('score') ?? 0);
              const requireAnswer = Number.isFinite(score) ? score > 0 : true;
              if (type === 'judgment') {
                return (
                  <Form.Item
                    name="answer"
                    label="正确答案"
                    rules={requireAnswer ? [{ required: true, message: '请选择正确答案' }] : []}
                  >
                    <Select placeholder="选择正确答案">
                      <Option value="正确">正确</Option>
                      <Option value="错误">错误</Option>
                    </Select>
                  </Form.Item>
                );
              }
              return (
                <Form.Item
                  name="answer"
                  label="正确答案"
                  rules={requireAnswer ? [{ required: true, message: '请输入正确答案' }] : []}
                >
                  <Input placeholder={type === 'multiple' ? '多个答案用逗号分隔' : '请输入正确答案'} />
                </Form.Item>
              );
            }}
          </Form.Item>

          <Form.Item name="analysis" label="解析">
            <TextArea rows={3} maxLength={255} showCount placeholder="请输入解析（可为空）" />
          </Form.Item>

          <Form.Item className="mb-0">
            <Space className="flex justify-end">
              <Button onClick={() => setModalVisible(false)}>取消</Button>
              <Button type="primary" htmlType="submit">
                {editingQuestion ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </GlassCard>
  );
};

export default QuestionManagePage;
