import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Space, Card, Modal, Form, message, Popconfirm, Tabs, Select } from 'antd';
import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import axios from 'axios';
import API_BASE_URL from '../config';

const DictionaryManagement = () => {
  const [data, setData] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [activeTab, setActiveTab] = useState('organizations');
  const [form] = Form.useForm();

  const tabs = [
    { key: 'departments', label: '部门管理' },
    { key: 'organizations', label: '单位名称' },
    { key: 'award-types', label: '奖励种类' },
    { key: 'award-levels', label: '奖励等级' },
    { key: 'paper-types', label: '论文种类' },
    { key: 'standard-types', label: '标准种类' },
    { key: 'project-categories', label: '项目分类' },
    { key: 'leader-departments', label: '领导层部门' },
  ];

  useEffect(() => {
    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeTab]);

  const fetchData = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('token');
      // 部门管理原本有自己的接口，现在统一走字典接口
      const response = await axios.get(`${API_BASE_URL}/api/dictionaries/${activeTab}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      setData(response.data);

      // 如果是领导层部门管理，还需要获取所有部门列表供选择
      if (activeTab === 'leader-departments') {
        const deptResponse = await axios.get(`${API_BASE_URL}/api/dictionaries/departments`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        setDepartments(deptResponse.data);
      }
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAddOrEdit = async (values) => {
    try {
      const token = localStorage.getItem('token');
      if (editingRecord) {
        await axios.put(`${API_BASE_URL}/api/dictionaries/${activeTab}/${editingRecord.id}`, values, {
          headers: { Authorization: `Bearer ${token}` }
        });
        message.success('修改成功');
      } else {
        await axios.post(`${API_BASE_URL}/api/dictionaries/${activeTab}`, values, {
          headers: { Authorization: `Bearer ${token}` }
        });
        message.success('添加成功');
      }
      setIsModalVisible(false);
      setEditingRecord(null);
      form.resetFields();
      fetchData();
    } catch (error) {
      message.error(error.response?.data?.message || '操作失败');
    }
  };

  const handleDelete = async (id) => {
    try {
      await axios.delete(`${API_BASE_URL}/api/dictionaries/${activeTab}/${id}`, {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      });
      message.success('删除成功');
      fetchData();
    } catch (error) {
      message.error(error.response?.data?.message || '删除失败');
    }
  };

  const openEditModal = (record) => {
    setEditingRecord(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (text) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => openEditModal(record)}
            disabled={record.name === '待定'}
          >
            修改
          </Button>
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
            disabled={record.name === '待定'}
          >
            <Button 
              type="link" 
              danger 
              icon={<DeleteOutlined />}
              disabled={record.name === '待定'}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <Card title="系统字典管理">
      <Tabs 
        activeKey={activeTab} 
        onChange={setActiveTab}
        items={tabs}
        tabBarExtraContent={
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={() => {
              setEditingRecord(null);
              form.resetFields();
              setIsModalVisible(true);
            }}
          >
            添加选项
          </Button>
        }
      />
      <Table 
        columns={columns} 
        dataSource={data} 
        rowKey="id" 
        loading={loading}
        pagination={{ pageSize: 10 }}
      />

      <Modal
        title={`${editingRecord ? '修改' : '添加'}${tabs.find(t => t.key === activeTab)?.label}`}
        open={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false);
          setEditingRecord(null);
        }}
        onOk={() => form.submit()}
        destroyOnClose
      >
        <Form form={form} onFinish={handleAddOrEdit} layout="vertical">
          {activeTab === 'leader-departments' ? (
            <Form.Item
              name="name"
              label="选择部门"
              rules={[{ required: true, message: '请选择部门' }]}
            >
              <Select placeholder="请选择部门" showSearch optionFilterProp="children">
                {departments.map(dept => (
                  <Select.Option key={dept.id} value={dept.name}>{dept.name}</Select.Option>
                ))}
              </Select>
            </Form.Item>
          ) : (
            <Form.Item
              name="name"
              label="名称"
              rules={[{ required: true, message: '请输入名称' }]}
            >
              <Input placeholder="请输入名称" />
            </Form.Item>
          )}
        </Form>
      </Modal>
    </Card>
  );
};

export default DictionaryManagement;
