import { useEffect, useMemo, useState } from 'react'
import {
  Alert,
  Button,
  Card,
  Drawer,
  Form,
  Input,
  InputNumber,
  Modal,
  Select,
  Space,
  Switch,
  Table,
  Tag,
  Typography,
  message,
} from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { authorityApi, menuApi } from '@/lib/api'
import { flattenAuthorities, flattenMenusForOptions } from '@/lib/tree'
import type { Authority, MenuNode } from '@/types/system'

export function MenuManagementPage() {
  const [form] = Form.useForm()
  const [menus, setMenus] = useState<MenuNode[]>([])
  const [roles, setRoles] = useState<Authority[]>([])
  const [loading, setLoading] = useState(false)
  const [modalOpen, setModalOpen] = useState(false)
  const [saving, setSaving] = useState(false)
  const [editingMenu, setEditingMenu] = useState<MenuNode | null>(null)
  const [drawerOpen, setDrawerOpen] = useState(false)
  const [activeMenu, setActiveMenu] = useState<MenuNode | null>(null)
  const [selectedRoles, setSelectedRoles] = useState<number[]>([])
  const [defaultRouterRoles, setDefaultRouterRoles] = useState<number[]>([])
  const [savingRoles, setSavingRoles] = useState(false)

  const roleOptions = useMemo(
    () =>
      flattenAuthorities(roles).map((item) => ({
        label: `${'　'.repeat(item.depth)}${item.authorityName} (${item.authorityId})`,
        value: item.authorityId,
      })),
    [roles],
  )

  const menuOptions = useMemo(
    () =>
      flattenMenusForOptions(menus).map((item) => ({
        label: `${'　'.repeat(item.depth)}${item.meta.title}`,
        value: item.ID,
      })),
    [menus],
  )

  const reloadMenus = async () => {
    setLoading(true)
    try {
      const [menuRes, roleRes] = await Promise.all([menuApi.getBaseMenuTree(), authorityApi.getAuthorityList()])
      setMenus(menuRes.data.menus)
      setRoles(roleRes.data)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    reloadMenus()
  }, [])

  const openCreate = (parentId = 0) => {
    setEditingMenu(null)
    form.resetFields()
    form.setFieldsValue({
      parentId,
      sort: 1,
      hidden: false,
      keepAlive: false,
      closeTab: false,
    })
    setModalOpen(true)
  }

  const openEdit = async (record: MenuNode) => {
    const response = await menuApi.getBaseMenuById(record.ID)
    const menu = response.data.menu
    setEditingMenu(menu)
    form.setFieldsValue({
      parentId: menu.parentId,
      title: menu.meta.title,
      name: menu.name,
      path: menu.path,
      component: menu.component,
      icon: menu.meta.icon,
      sort: menu.sort,
      hidden: menu.hidden,
      keepAlive: menu.meta.keepAlive,
      closeTab: menu.meta.closeTab,
    })
    setModalOpen(true)
  }

  const saveMenu = async () => {
    const values = await form.validateFields()
    const payload = {
      ID: editingMenu?.ID,
      parentId: values.parentId || 0,
      name: values.name,
      path: values.path,
      component: values.component,
      sort: values.sort,
      hidden: Boolean(values.hidden),
      meta: {
        title: values.title,
        icon: values.icon,
        keepAlive: Boolean(values.keepAlive),
        closeTab: Boolean(values.closeTab),
      },
    }

    setSaving(true)
    try {
      if (editingMenu) {
        await menuApi.updateBaseMenu(payload)
        message.success('菜单已更新')
      } else {
        await menuApi.addBaseMenu(payload)
        message.success('菜单已创建')
      }
      setModalOpen(false)
      reloadMenus()
    } finally {
      setSaving(false)
    }
  }

  const deleteMenu = (record: MenuNode) => {
    Modal.confirm({
      title: `删除菜单 ${record.meta.title}`,
      content: '如果该菜单已被角色使用，删除前请先调整菜单授权。',
      okButtonProps: { danger: true },
      onOk: async () => {
        await menuApi.deleteBaseMenu(record.ID)
        message.success('菜单已删除')
        reloadMenus()
      },
    })
  }

  const openRoleDrawer = async (record: MenuNode) => {
    const response = await menuApi.getMenuRoles(record.ID)
    setActiveMenu(record)
    setSelectedRoles(response.data.authorityIds)
    setDefaultRouterRoles(response.data.defaultRouterAuthorityIds)
    setDrawerOpen(true)
  }

  const saveRoles = async () => {
    if (!activeMenu) {
      return
    }
    setSavingRoles(true)
    try {
      await menuApi.setMenuRoles({
        menuId: activeMenu.ID,
        authorityIds: selectedRoles,
      })
      message.success('菜单角色关系已更新')
      setDrawerOpen(false)
    } finally {
      setSavingRoles(false)
    }
  }

  const columns: ColumnsType<MenuNode> = [
    { title: 'ID', dataIndex: 'ID', width: 80 },
    {
      title: '展示名称',
      width: 180,
      render: (_, record) => record.meta.title,
    },
    { title: '路由 Name', dataIndex: 'name', width: 140 },
    { title: '路由 Path', dataIndex: 'path', width: 180 },
    { title: '组件路径', dataIndex: 'component', width: 280 },
    {
      title: '状态',
      width: 180,
      render: (_, record) => (
        <Space wrap>
          <Tag color={record.hidden ? 'default' : 'green'}>{record.hidden ? '隐藏' : '显示'}</Tag>
          {record.meta.keepAlive ? <Tag color="blue">KeepAlive</Tag> : null}
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 260,
      fixed: 'right',
      render: (_, record) => (
        <Space wrap>
          <Button type="link" onClick={() => openCreate(record.ID)}>
            添加子菜单
          </Button>
          <Button type="link" onClick={() => openEdit(record)}>
            编辑
          </Button>
          <Button type="link" onClick={() => openRoleDrawer(record)}>
            分配角色
          </Button>
          <Button danger type="link" onClick={() => deleteMenu(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ]

  return (
    <div className="page-stack">
      <Card className="glass-panel page-panel">
        <div className="section-heading">
          <div>
            <Typography.Title level={2} style={{ marginBottom: 8 }}>
              菜单管理
            </Typography.Title>
            <Typography.Paragraph className="text-muted" style={{ marginBottom: 0 }}>
              当前页直接维护后端基础菜单树，保证新 React 后台与原权限模型保持一致。
            </Typography.Paragraph>
          </div>
          <Button type="primary" onClick={() => openCreate()}>
            新建根菜单
          </Button>
        </div>
        <Table
          rowKey="ID"
          loading={loading}
          columns={columns}
          dataSource={menus}
          expandable={{ defaultExpandAllRows: true }}
          pagination={false}
          scroll={{ x: 1300 }}
        />
      </Card>

      <Modal
        open={modalOpen}
        title={editingMenu ? '编辑菜单' : '新建菜单'}
        onCancel={() => setModalOpen(false)}
        onOk={saveMenu}
        confirmLoading={saving}
        width={760}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="parentId" label="父菜单">
            <Select options={[{ label: '根菜单', value: 0 }, ...menuOptions]} />
          </Form.Item>
          <Form.Item name="title" label="展示名称" rules={[{ required: true, message: '请输入展示名称' }]}>
            <Input />
          </Form.Item>
          <Space.Compact block>
            <Form.Item
              name="name"
              label="路由 Name"
              rules={[{ required: true, message: '请输入路由 Name' }]}
              style={{ width: '50%' }}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="path"
              label="路由 Path"
              rules={[{ required: true, message: '请输入路由 Path' }]}
              style={{ width: '50%' }}
            >
              <Input />
            </Form.Item>
          </Space.Compact>
          <Form.Item
            name="component"
            label="组件路径"
            rules={[{ required: true, message: '请输入组件路径' }]}
          >
            <Input placeholder="例如：view/superAdmin/user/user.vue" />
          </Form.Item>
          <Space.Compact block>
            <Form.Item name="icon" label="图标名" style={{ width: '60%' }}>
              <Input />
            </Form.Item>
            <Form.Item name="sort" label="排序" style={{ width: '40%' }}>
              <InputNumber style={{ width: '100%' }} min={0} />
            </Form.Item>
          </Space.Compact>
          <Space size="large">
            <Form.Item name="hidden" label="隐藏" valuePropName="checked">
              <Switch />
            </Form.Item>
            <Form.Item name="keepAlive" label="KeepAlive" valuePropName="checked">
              <Switch />
            </Form.Item>
            <Form.Item name="closeTab" label="自动关闭 Tab" valuePropName="checked">
              <Switch />
            </Form.Item>
          </Space>
        </Form>
      </Modal>

      <Drawer
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        title={activeMenu ? `菜单角色分配 · ${activeMenu.meta.title}` : '菜单角色分配'}
        width={520}
        extra={
          <Button type="primary" loading={savingRoles} onClick={saveRoles}>
            保存
          </Button>
        }
      >
        {defaultRouterRoles.length ? (
          <Alert
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
            message={`有 ${defaultRouterRoles.length} 个角色将当前菜单设为默认首页，调整前请确认首页策略。`}
          />
        ) : null}
        <Select
          mode="multiple"
          style={{ width: '100%' }}
          value={selectedRoles}
          options={roleOptions}
          onChange={setSelectedRoles}
        />
      </Drawer>
    </div>
  )
}
