/**
 * KRA - Menu Management Page
 * Manage system menus with tree structure CRUD operations
 */
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, message, Popconfirm, Tag, Space, Drawer } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import * as Icons from '@ant-design/icons';
import { getMenuList, deleteBaseMenu, getBaseMenuById } from '@/services/kratos/menu';
import WarningBar from '@/components/WarningBar/WarningBar';
import MenuForm from './components/MenuForm';

export interface MenuItem {
  ID: number;
  parentId: number;
  path: string;
  name: string;
  hidden: boolean;
  component: string;
  sort: number;
  meta: {
    title: string;
    icon: string;
    keepAlive: boolean;
    defaultMenu: boolean;
    closeTab: boolean;
    activeName?: string;
    transitionType?: string;
  };
  children?: MenuItem[];
  parameters?: Array<{ ID?: number; type: string; key: string; value: string }>;
  menuBtn?: Array<{ ID?: number; name: string; desc: string }>;
}

const MenuPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState<MenuItem | null>(null);
  const [dialogFlag, setDialogFlag] = useState<'add' | 'edit'>('add');
  const [parentId, setParentId] = useState<number>(0);
  const [tableData, setTableData] = useState<MenuItem[]>([]);

  // 获取菜单列表
  const fetchMenuList = async () => {
    try {
      const res = await getMenuList({ page: 1, pageSize: 999 });
      if (res.code === 0) {
        setTableData(res.data?.list || res.data || []);
      }
    } catch (error) {
      console.error('Failed to fetch menu list:', error);
    }
  };

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

  // 渲染图标
  const renderIcon = (iconName: string) => {
    if (!iconName) return null;
    const IconComponent = (Icons as any)[iconName] || (Icons as any)[`${iconName}Outlined`];
    return IconComponent ? <IconComponent style={{ marginRight: 8 }} /> : null;
  };

  // 添加菜单
  const handleAddMenu = (pid: number = 0) => {
    setParentId(pid);
    setCurrentRow(null);
    setDialogFlag('add');
    setDrawerVisible(true);
  };

  // 编辑菜单
  const handleEditMenu = async (id: number) => {
    try {
      const res = await getBaseMenuById({ id });
      if (res.code === 0 && res.data?.menu) {
        setCurrentRow(res.data.menu);
        setDialogFlag('edit');
        setDrawerVisible(true);
      }
    } catch (error) {
      message.error('获取菜单信息失败');
    }
  };

  // 删除菜单
  const handleDeleteMenu = async (id: number) => {
    try {
      const res = await deleteBaseMenu({ ID: id });
      if (res.code === 0) {
        message.success('删除成功');
        fetchMenuList();
        actionRef.current?.reload();
      } else {
        message.error(res.msg || '删除失败');
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 表格列定义
  const columns: ProColumns<MenuItem>[] = [
    {
      title: 'ID',
      dataIndex: 'ID',
      width: 80,
      search: false,
    },
    {
      title: '展示名称',
      dataIndex: ['meta', 'title'],
      width: 150,
      search: false,
      render: (_, record) => record.meta?.title || '-',
    },
    {
      title: '图标',
      dataIndex: ['meta', 'icon'],
      width: 140,
      search: false,
      render: (_, record) => {
        const iconName = record.meta?.icon;
        if (!iconName) return '-';
        return (
          <Space>
            {renderIcon(iconName)}
            <span>{iconName}</span>
          </Space>
        );
      },
    },
    {
      title: '路由Name',
      dataIndex: 'name',
      width: 160,
      ellipsis: true,
      search: false,
    },
    {
      title: '路由Path',
      dataIndex: 'path',
      width: 160,
      ellipsis: true,
      search: false,
    },
    {
      title: '是否隐藏',
      dataIndex: 'hidden',
      width: 100,
      search: false,
      render: (_, record) => (
        <Tag color={record.hidden ? 'red' : 'green'}>
          {record.hidden ? '隐藏' : '显示'}
        </Tag>
      ),
    },
    {
      title: '父节点',
      dataIndex: 'parentId',
      width: 90,
      search: false,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      width: 70,
      search: false,
    },
    {
      title: '文件路径',
      dataIndex: 'component',
      width: 300,
      ellipsis: true,
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 250,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="addChild"
          type="link"
          size="small"
          icon={<PlusOutlined />}
          onClick={() => handleAddMenu(record.ID)}
        >
          添加子菜单
        </Button>,
        <Button
          key="edit"
          type="link"
          size="small"
          icon={<EditOutlined />}
          onClick={() => handleEditMenu(record.ID)}
        >
          编辑
        </Button>,
        <Popconfirm
          key="delete"
          title="此操作将永久删除所有角色下该菜单, 是否继续?"
          onConfirm={() => handleDeleteMenu(record.ID)}
          okText="确定"
          cancelText="取消"
        >
          <Button type="link" size="small" danger icon={<DeleteOutlined />}>
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <WarningBar title="新增菜单，需要在角色管理内配置权限才可使用" type="warning" />
      <ProTable<MenuItem>
        actionRef={actionRef}
        columns={columns}
        rowKey="ID"
        scroll={{ x: 1500 }}
        dataSource={tableData}
        search={false}
        pagination={false}
        expandable={{
          defaultExpandAllRows: false,
          childrenColumnName: 'children',
        }}
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => handleAddMenu(0)}
          >
            新增根菜单
          </Button>,
        ]}
      />

      {/* 菜单表单抽屉 */}
      <MenuForm
        visible={drawerVisible}
        onClose={() => {
          setDrawerVisible(false);
          setCurrentRow(null);
        }}
        onSuccess={() => {
          setDrawerVisible(false);
          setCurrentRow(null);
          fetchMenuList();
          actionRef.current?.reload();
        }}
        initialValues={currentRow}
        dialogFlag={dialogFlag}
        parentId={parentId}
        menuList={tableData}
      />
    </PageContainer>
  );
};

export default MenuPage;
