import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Space, App, Popconfirm, Modal, Form, Tag, Tooltip } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { useLocation } from 'react-router-dom';
import api from '../../services/api';
import { getCategoryColorHex } from '../../lib/categoryColors';
import { formatDateTime } from '../../utils/validation';
import GlassCard from '../../components/common/GlassCard';

interface QuestionCategory {
  id: string;
  name: string;
  createdAt: string;
  questionCount?: number;
}

const QuestionCategoryPage = () => {
  const { message } = App.useApp();
  const [categories, setCategories] = useState<QuestionCategory[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingCategory, setEditingCategory] = useState<QuestionCategory | null>(null);
  const [form] = Form.useForm();
  const location = useLocation(); // 添加路由监听

  const fetchCategories = async () => {
    setLoading(true);
    try {
      const res = await api.get('/question-categories');
      setCategories(res.data);
    } catch (error) {
      message.error('获取题目类别失败');
    } finally {
      setLoading(false);
    }
  };

  // 当路由变化或组件挂载时重新获取类别列表
  useEffect(() => {
    fetchCategories();
  }, [location.pathname]); // 监听路由变化

  // 手动刷新类别列表
  const handleRefresh = () => {
    fetchCategories();
  };

  const handleCreate = () => {
    setEditingCategory(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (category: QuestionCategory) => {
    setEditingCategory(category);
    form.setFieldsValue({ name: category.name });
    setModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/admin/question-categories/${id}`);
      message.success('删除成功');
      fetchCategories();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingCategory) {
        await api.put(`/admin/question-categories/${editingCategory.id}`, values);
        message.success('更新成功');
      } else {
        await api.post('/admin/question-categories', values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchCategories();
    } catch (error) {
      message.error('操作失败');
    }
  };

  const columns = [
    {
      title: '类别名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center' as const,
      width: 250,
      render: (name: string) => (
        <div className="flex items-center">
          <Tag color={getCategoryColorHex(name)} className="mr-2">
            {name}
          </Tag>
        </div>
      ),
    },
    {
      title: (
        <Tooltip title="该类别下题目数量（按题目表 category 统计）">
          <span>题库数量</span>
        </Tooltip>
      ),
      dataIndex: 'questionCount',
      key: 'questionCount',
      align: 'center' as const,
      width: 120,
      className: 'qc-question-count-td',
      sorter: (a: QuestionCategory, b: QuestionCategory) => (a.questionCount ?? 0) - (b.questionCount ?? 0),
      render: (count: number | undefined) => (
        <div className="qc-question-count">{count ?? 0}</div>
      ),
    },
    {
      title: '创建时间',
      align: 'center' as const,
      width: 200,
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text: string) => formatDateTime(text, { includeSeconds: true }),
    },
    {
      title: <div style={{ textAlign: 'center' }}>操作</div>,
      key: 'action',
      align: 'center' as const,
      width: 200,
      render: (_: any, record: QuestionCategory) => (
        <Space>
          <Button
            type="text"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除该类别吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="text" size="small" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <GlassCard>
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold text-white">题目类别管理</h1>
        <Space>
          <Button icon={<EditOutlined spin={loading} />} onClick={handleRefresh}>
            刷新类别
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
            新增类别
          </Button>
        </Space>
      </div>

      <Table
        columns={columns}
        dataSource={categories}
        rowKey="id"
        size="small"
        loading={loading}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
        }}
      />

      <Modal
        title={editingCategory ? '编辑类别' : '新增类别'}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="类别名称"
            rules={[{ required: true, message: '请输入类别名称' }]}
          >
            <Input placeholder="请输入类别名称" />
          </Form.Item>
        </Form>
      </Modal>
    </GlassCard>
  );
};

export default QuestionCategoryPage;
