import { Tag, Tree } from 'antd';
import { useQuery } from '@tanstack/react-query';
import { ProCard } from '@ant-design/pro-components';
import { IconCategory } from '@tabler/icons-react';
import PageContainer from '@/components/common/PageContainer';
import { menuApi, MenuResp } from '@/api/menu';

interface TreeNode { key: string; title: any; children?: TreeNode[]; }

function toTree(menus: MenuResp[]): TreeNode[] {
  return menus.map((m) => ({
    key: String(m.menuId),
    title: (
      <span>
        <Tag color={m.menuType === 'DIRECTORY' ? 'blue' : 'default'} style={{ marginRight: 6 }}>
          {m.menuType}
        </Tag>
        <strong>{m.menuName}</strong>
        <span style={{ color: '#999', marginLeft: 8, fontSize: 12 }}>
          {m.menuPath ?? m.menuCode}
        </span>
      </span>
    ),
    children: m.children?.length ? toTree(m.children) : undefined,
  }));
}

export default function MenuManage() {
  const { data: tree = [] } = useQuery({
    queryKey: ['menu', 'tree'],
    queryFn: menuApi.tree,
  });

  return (
    <PageContainer title="메뉴 관리" description="시스템 메뉴 트리 / 표시 / 권한 매핑">
      <ProCard
        title={<span><IconCategory size={16} style={{ verticalAlign: -3 }} /> 메뉴 트리</span>}
        headerBordered
        bordered={false}
        extra={<Tag color="processing">전체 {countMenus(tree)}개</Tag>}
      >
        <Tree
          treeData={toTree(tree) as any}
          defaultExpandAll
          showLine={{ showLeafIcon: false }}
          style={{ minHeight: 400 }}
        />
      </ProCard>
    </PageContainer>
  );
}

function countMenus(menus: MenuResp[]): number {
  return menus.reduce((sum, m) => sum + 1 + (m.children ? countMenus(m.children) : 0), 0);
}
