import {
  Table,
  Button,
  Space,
  Form,
  Input,
  InputNumber,
  Select,
  Switch,
  TreeSelect,
  Popconfirm,
  Typography,
  Tag,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import {
  getMenus,
  createMenu,
  updateMenu,
  deleteMenu,
  type MenuInfo,
  type MenuItemReq,
} from '../../api/menus';
import { useListData } from '../../hooks/useListData';
import { useCrudDrawer } from '../../hooks/useCrudDrawer';
import { DrawerForm } from '../../components/DrawerForm';
import { useApiRequest } from '../../hooks/useApiRequest';

type MenuItem = MenuInfo;

function toTreeSelectData(items: MenuItem[]): Array<{ title: string; value: string; children?: Array<{ title: string; value: string }> }> {
  return items.map((item) => ({
    title: item.title,
    value: item.id,
    children: item.children?.length ? toTreeSelectData(item.children) : undefined,
  }));
}

const MENU_TYPE_LABELS: Record<string, { text: string; color: string }> = {
  directory: { text: '目录', color: 'blue' },
  menu: { text: '菜单', color: 'green' },
  button: { text: '按钮', color: 'orange' },
};

export default function MenuConfig() {
  const { data: menuTree, loading, refresh } = useListData<MenuItem>(getMenus);

  const { execute } = useApiRequest();

  const drawer = useCrudDrawer<MenuItem>({
    getId: (r) => r.id,
    onCreate: async (values) => {
      await createMenu(values as unknown as MenuItemReq);
    },
    onUpdate: async (id, values) => {
      await updateMenu(id, values as unknown as MenuItemReq & { version: number });
    },
    onSuccess: refresh,
  });

  const handleDelete = async (id: string, version: number) => {
    await execute(() => deleteMenu(id, version), '菜单已删除');
    refresh();
  };

  const columns = [
    { title: '标题', dataIndex: 'title', key: 'title', width: 200 },
    { title: '路径', dataIndex: 'path', key: 'path', ellipsis: true, render: (v?: string) => v || '-' },
    { title: '图标', dataIndex: 'icon', key: 'icon', width: 100, render: (v?: string) => v || '-' },
    {
      title: '类型', dataIndex: 'menu_type', key: 'menu_type', width: 90,
      render: (v: string) => {
        const info = MENU_TYPE_LABELS[v] ?? { text: v, color: 'default' };
        return <Tag color={info.color}>{info.text}</Tag>;
      },
    },
    { title: '排序', dataIndex: 'sort_order', key: 'sort_order', width: 80 },
    {
      title: '可见', dataIndex: 'visible', key: 'visible', width: 80,
      render: (v: boolean) => v ? <Tag color="green">是</Tag> : <Tag color="default">否</Tag>,
    },
    {
      title: '操作', key: 'actions', width: 150,
      render: (_: unknown, record: MenuItem) => (
        <Space>
          <Button size="small" onClick={() => drawer.openEdit(record, (r) => ({
            parent_id: r.parent_id || undefined,
            title: r.title,
            path: r.path,
            icon: r.icon,
            menu_type: r.menu_type,
            sort_order: r.sort_order,
            visible: r.visible,
            permission: r.permission,
          }))}>编辑</Button>
          <Popconfirm title="确定删除此菜单？" onConfirm={() => handleDelete(record.id, record.version)}>
            <Button size="small" danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <Typography.Title level={5} style={{ margin: 0 }}>菜单配置</Typography.Title>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => drawer.openCreate({ menu_type: 'menu', sort_order: 0, visible: true })}
        >
          添加菜单
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={menuTree}
        rowKey="id"
        loading={loading}
        pagination={false}
        indentSize={20}
      />

      <DrawerForm
        title={drawer.editingRecord ? '编辑菜单' : '添加菜单'}
        open={drawer.open}
        onClose={drawer.close}
        onSubmit={drawer.handleSubmit}
        initialValues={drawer.initialValues}
        loading={drawer.loading}
        width={520}
        columns={1}
      >
        <Form.Item name="parent_id" label="上级菜单">
          <TreeSelect
            treeData={toTreeSelectData(menuTree)}
            placeholder="无（顶级菜单）"
            allowClear
            treeDefaultExpandAll
          />
        </Form.Item>
        <Form.Item name="title" label="标题" rules={[{ required: true, message: '请输入菜单标题' }]}>
          <Input />
        </Form.Item>
        <Form.Item name="path" label="路径">
          <Input placeholder="/example/path" />
        </Form.Item>
        <Form.Item name="icon" label="图标">
          <Input placeholder="图标名称，如 HomeOutlined" />
        </Form.Item>
        <Form.Item name="menu_type" label="类型" rules={[{ required: true, message: '请选择菜单类型' }]}>
          <Select options={[
            { label: '目录', value: 'directory' },
            { label: '菜单', value: 'menu' },
            { label: '按钮', value: 'button' },
          ]} />
        </Form.Item>
        <Form.Item name="sort_order" label="排序" initialValue={0}>
          <InputNumber min={0} style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item name="visible" label="可见" valuePropName="checked" initialValue>
          <Switch />
        </Form.Item>
        <Form.Item name="permission" label="权限标识">
          <Input placeholder="如 system:user:list" />
        </Form.Item>
      </DrawerForm>
    </div>
  );
}
