import React, { useEffect, useState } from 'react';
import { Card, Table, Button, Modal, Form, Input, Space, message, Select, TreeSelect, Tooltip, Switch } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import * as service from './service';
import { MenuTypeEnum, MenuResponse, MenuRequest } from './types';
import IconSelect from '@/components/IconSelect';
import { useDispatch } from 'react-redux';
import { setMenus } from '@/store/userSlice';
import { getIconComponent } from '@/config/icons.tsx';

const MenuPage: React.FC = () => {
    const dispatch = useDispatch();
    const [form] = Form.useForm();
    const [modalVisible, setModalVisible] = useState(false);
    const [editingMenu, setEditingMenu] = useState<MenuResponse | null>(null);
    const [iconSelectVisible, setIconSelectVisible] = useState(false);
    const [loading, setLoading] = useState(false);
    const [menuTree, setMenuTree] = useState<MenuResponse[]>([]);

    // 加载菜单树
    const loadMenuTree = async () => {
        try {
            setLoading(true);
            const data = await service.getMenuTree();
            setMenuTree(data);
        } catch (error) {
            message.error('加载菜单数据失败');
        } finally {
            setLoading(false);
        }
    };

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

    const handleAdd = () => {
        setEditingMenu(null);
        form.resetFields();
        form.setFieldsValue({
            type: MenuTypeEnum.MENU,
            sort: 1,
            hidden: false
        });
        setModalVisible(true);
    };

    const handleEdit = (record: MenuResponse) => {
        setEditingMenu(record);
        form.setFieldsValue({
            ...record,
            parentId: record.parentId === 0 ? undefined : record.parentId
        });
        setModalVisible(true);
    };

    const handleDelete = async (id: number) => {
        try {
            await service.deleteMenu(id);
            message.success('删除成功');
            loadMenuTree();
            await updateReduxMenus();
        } catch (error) {
            message.error('删除失败');
        }
    };

    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();
            if (editingMenu) {
                await service.updateMenu(editingMenu.id, {
                    ...values,
                    version: editingMenu.version
                });
                message.success('更新成功');
            } else {
                await service.createMenu(values);
                message.success('创建成功');
            }
            setModalVisible(false);
            loadMenuTree();
            await updateReduxMenus();
        } catch (error) {
            message.error('操作失败');
        }
    };

    // 更新 Redux 中的菜单数据
    const updateReduxMenus = async () => {
        try {
            const menus = await service.getCurrentUserMenus();
            dispatch(setMenus(menus));
        } catch (error) {
            console.error('更新菜单数据失败:', error);
        }
    };

    const getTreeSelectData = (menuList: MenuResponse[]) => {
        return menuList.map(menu => ({
            title: menu.name,
            value: menu.id,
            children: menu.children?.map(child => ({
                title: child.name,
                value: child.id,
                disabled: editingMenu?.id === child.id
            }))
        }));
    };

    const columns: ColumnsType<MenuResponse> = [
        {
            title: '菜单名称',
            dataIndex: 'name',
            width: 200
        },
        {
            title: '图标',
            dataIndex: 'icon',
            width: 100,
            render: (icon: string) => {
                return getIconComponent(icon);
            }
        },
        {
            title: '路由地址',
            dataIndex: 'path',
            width: 200
        },
        {
            title: '组件路径',
            dataIndex: 'component',
            width: 200
        },
        {
            title: '菜单类型',
            dataIndex: 'type',
            width: 120,
            render: (type: MenuTypeEnum) => {
                const typeMap = {
                    [MenuTypeEnum.DIRECTORY]: '目录',
                    [MenuTypeEnum.MENU]: '菜单',
                    [MenuTypeEnum.BUTTON]: '按钮'
                };
                return typeMap[type];
            }
        },
        {
            title: '显示排序',
            dataIndex: 'sort',
            width: 100
        },
        {
            title: '操作',
            key: 'action',
            width: 200,
            render: (_, record) => (
                <Space>
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button
                        type="link"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleDelete(record.id)}
                        disabled={record.children?.length > 0}
                    >
                        删除
                    </Button>
                </Space>
            )
        }
    ];

    return (
        <Card>
            <div style={{ marginBottom: 16 }}>
                <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={handleAdd}
                >
                    新增菜单
                </Button>
            </div>

            <Table
                columns={columns}
                dataSource={menuTree}
                rowKey="id"
                loading={loading}
                pagination={false}
                size="middle"
                bordered
                defaultExpandAllRows
            />

            <Modal
                title={editingMenu ? '编辑菜单' : '新增菜单'}
                open={modalVisible}
                onOk={handleSubmit}
                onCancel={() => setModalVisible(false)}
                width={600}
            >
                <Form
                    form={form}
                    layout="vertical"
                >
                    <Form.Item
                        name="type"
                        label="菜单类型"
                        rules={[{ required: true, message: '请选择菜单类型' }]}
                    >
                        <Select>
                            <Select.Option value={MenuTypeEnum.DIRECTORY}>目录</Select.Option>
                            <Select.Option value={MenuTypeEnum.MENU}>菜单</Select.Option>
                            <Select.Option value={MenuTypeEnum.BUTTON}>按钮</Select.Option>
                        </Select>
                    </Form.Item>

                    <Form.Item
                        name="name"
                        label="菜单名称"
                        rules={[{ required: true, message: '请输入菜单名称' }]}
                    >
                        <Input placeholder="请输入菜单名称" />
                    </Form.Item>

                    <Form.Item
                        name="parentId"
                        label={
                            <span>
                                上级菜单
                                <Tooltip title="不选择则为顶级菜单">
                                    <QuestionCircleOutlined style={{ marginLeft: 4 }} />
                                </Tooltip>
                            </span>
                        }
                    >
                        <TreeSelect
                            treeData={getTreeSelectData(menuTree)}
                            placeholder="不选择则为顶级菜单"
                            allowClear
                            treeDefaultExpandAll
                            showSearch
                            treeNodeFilterProp="title"
                        />
                    </Form.Item>

                    <Form.Item
                        noStyle
                        shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}
                    >
                        {({ getFieldValue }) => {
                            const type = getFieldValue('type');
                            if (type === MenuTypeEnum.BUTTON) {
                                return null;
                            }
                            return (
                                <>
                                    <Form.Item
                                        name="icon"
                                        label="菜单图标"
                                    >
                                        <Input
                                            placeholder="请选择图标"
                                            readOnly
                                            onClick={() => setIconSelectVisible(true)}
                                            suffix={getIconComponent(form.getFieldValue('icon'))}
                                        />
                                    </Form.Item>

                                    <Form.Item
                                        name="path"
                                        label="路由地址"
                                        rules={[{ required: true, message: '请输入路由地址' }]}
                                    >
                                        <Input placeholder="请输入路由地址" />
                                    </Form.Item>

                                    {type === MenuTypeEnum.MENU && (
                                        <Form.Item
                                            name="component"
                                            label="组件路径"
                                            rules={[{ required: true, message: '请输入组件路径' }]}
                                        >
                                            <Input placeholder="请输入组件路径" />
                                        </Form.Item>
                                    )}
                                </>
                            );
                        }}
                    </Form.Item>

                    <Form.Item
                        name="sort"
                        label="显示排序"
                        rules={[{ required: true, message: '请输入显示排序' }]}
                    >
                        <Input type="number" placeholder="请输入显示排序" />
                    </Form.Item>

                    <Form.Item
                        name="hidden"
                        label="是否隐藏"
                        valuePropName="checked"
                    >
                        <Switch checkedChildren="是" unCheckedChildren="否" />
                    </Form.Item>
                </Form>
            </Modal>

            <IconSelect
                visible={iconSelectVisible}
                onCancel={() => setIconSelectVisible(false)}
                value={form.getFieldValue('icon')}
                onChange={value => {
                    form.setFieldValue('icon', value);
                    setIconSelectVisible(false);
                }}
            />
        </Card>
    );
};

export default MenuPage; 