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

interface UserGroup {
  id: string;
  name: string;
  description: string;
  isSystem: boolean;
  createdAt: string;
  memberCount: number;
}

const UserGroupManage = () => {
  const { message } = App.useApp();
  const [groups, setGroups] = useState<UserGroup[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingGroup, setEditingGroup] = useState<UserGroup | null>(null);
  const [form] = Form.useForm();

  const fetchGroups = async () => {
    setLoading(true);
    try {
      const res = await userGroupAPI.getAll();
      setGroups(res.data);
    } catch (error) {
      message.error('获取用户组列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchGroups();
  }, []);

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

  const handleEdit = (group: UserGroup) => {
    if (group.isSystem) {
      message.warning('系统内置用户组无法修改');
      return;
    }
    setEditingGroup(group);
    form.setFieldsValue({
      name: group.name,
      description: group.description,
    });
    setModalVisible(true);
  };

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

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      
      if (editingGroup) {
        await userGroupAPI.update(editingGroup.id, values);
        message.success('更新成功');
      } else {
        await userGroupAPI.create(values);
        message.success('创建成功');
      }
      
      setModalVisible(false);
      fetchGroups();
    } catch (error: any) {
      message.error(error.message || '操作失败');
    }
  };

  const columns = [
    {
      title: '组名',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: UserGroup) => (
        <Space>
          {text}
          {record.isSystem && <Tag color="blue">系统内置</Tag>}
        </Space>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '成员数',
      dataIndex: 'memberCount',
      key: 'memberCount',
      render: (count: number) => (
        <Space>
          <TeamOutlined />
          {count}人
        </Space>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text: string) => formatDateTime(text),
    },
    {
      title: <div style={{ textAlign: 'center' }}>操作</div>,
      key: 'action',
      render: (_: any, record: UserGroup) => (
        <Space>
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            disabled={record.isSystem}
          >
            编辑
          </Button>
          {!record.isSystem && (
            <Popconfirm
              title="确定删除该用户组吗？"
              description="删除后，组内成员将自动解除与该组的关联"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="text" 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>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
          新增用户组
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={groups}
        rowKey="id"
        size="small"
        loading={loading}
        pagination={{ pageSize: 10, size: 'small' }}
      />

      <Modal
        title={editingGroup ? '编辑用户组' : '新增用户组'}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        okText="确定"
        cancelText="取消"
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="组名"
            rules={[
              { required: true, message: '请输入组名' },
              { min: 2, max: 20, message: '组名长度在2-20个字符之间' }
            ]}
          >
            <Input placeholder="请输入组名" />
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea placeholder="请输入描述" rows={3} />
          </Form.Item>
        </Form>
      </Modal>
    </GlassCard>
  );
};

export default UserGroupManage;
