/**
 * 角色管理页面
 *
 * - 角色列表展示
 * - 创建/编辑角色
 * - 权限树勾选（按模块分组）
 */

import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  Button,
  Card,
  Drawer,
  Form,
  Input,
  Message,
  Popconfirm,
  Space,
  Table,
  Tag,
  Tree,
  Typography,
} from '@arco-design/web-react';
import {
  fetchPermissions,
  fetchRoles,
  createRole,
  updateRole,
  deleteRole,
  setRolePermissions,
} from '@/api/permission';
import type { PermissionItem, Role } from '@/api/permission';
import { Permission } from '@/components/Permission';

/**
 * 权限树节点数据类型
 * @note Arco Design 未导出 TreeNodeData，此处自行定义
 */
interface TreeNodeData {
  key: string;
  title: string;
  children?: TreeNodeData[];
}

/** 权限码按模块分组 */
const PERM_GROUPS: Record<string, string> = {
  device: '设备管理',
  charge: '充电控制',
  charge_record: '充电记录',
  device_log: '设备日志',
  energy: '能耗管理',
  user: '用户管理',
  role: '角色管理',
  operation_log: '操作日志',
};

export default function RolesPage() {
  const [roles, setRoles] = useState<Role[]>([]);
  const [allPerms, setAllPerms] = useState<PermissionItem[]>([]);
  const [loading, setLoading] = useState(false);

  // 抽屉状态
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [formValues, setFormValues] = useState({ name: '', description: '' });
  const [selectedPerms, setSelectedPerms] = useState<string[]>([]);
  const [saving, setSaving] = useState(false);

  /** 加载角色列表和权限码 */
  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const [rolesData, permsData] = await Promise.all([
        fetchRoles(),
        fetchPermissions(),
      ]);
      setRoles(rolesData);
      setAllPerms(permsData);
    } catch {
      Message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  }, []);

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

  /** 构建权限树数据 */
  const treeData: TreeNodeData[] = buildPermTree(allPerms);
  /** 默认展开所有父节点（替代已移除的 defaultExpandAll） */
  const defaultExpandedKeys = useMemo(() => treeData.map((n) => n.key), [treeData]);

  /** 打开创建抽屉 */
  const handleCreate = () => {
    setEditingRole(null);
    setFormValues({ name: '', description: '' });
    setSelectedPerms([]);
    setDrawerVisible(true);
  };

  /** 打开编辑抽屉 */
  const handleEdit = (role: Role) => {
    setEditingRole(role);
    setFormValues({ name: role.name, description: role.description ?? '' });
    setSelectedPerms(role.permission_codes);
    setDrawerVisible(true);
  };

  /** 保存角色 */
  const handleSave = async () => {
    if (!formValues.name.trim()) {
      Message.warning('请输入角色名称');
      return;
    }

    setSaving(true);
    try {
      if (editingRole) {
        await updateRole(editingRole.id, formValues.name, formValues.description);
        await setRolePermissions(editingRole.id, selectedPerms);
        Message.success('更新成功');
      } else {
        const res = await createRole(formValues.name, formValues.description);
        const newRoleId = (res.data as { id: number })?.id;
        if (newRoleId && selectedPerms.length > 0) {
          await setRolePermissions(newRoleId, selectedPerms);
        }
        Message.success('创建成功');
      }
      setDrawerVisible(false);
      loadData();
    } catch {
      Message.error('保存失败');
    } finally {
      setSaving(false);
    }
  };

  /** 删除角色 */
  const handleDelete = async (id: number) => {
    try {
      await deleteRole(id);
      Message.success('删除成功');
      loadData();
    } catch {
      Message.error('删除失败');
    }
  };

  /** 表格列定义 */
  const columns = [
    { title: 'ID', dataIndex: 'id', width: 80 },
    { title: '角色名', dataIndex: 'name', width: 150 },
    { title: '描述', dataIndex: 'description' },
    {
      title: '权限',
      dataIndex: 'permission_codes',
      render: (_: unknown, record: Role) => (
        <Space wrap>
          {record.permission_codes.slice(0, 5).map((code) => (
            <Tag key={code} size="small">{code}</Tag>
          ))}
          {record.permission_codes.length > 5 && (
            <Tag size="small">+{record.permission_codes.length - 5}</Tag>
          )}
        </Space>
      ),
    },
    {
      title: '操作',
      width: 180,
      render: (_: unknown, record: Role) => (
        <Space>
          <Permission code="role:edit">
            <Button type="text" size="small" onClick={() => handleEdit(record)}>
              编辑
            </Button>
          </Permission>
          <Permission code="role:delete">
            <Popconfirm
              title="确认删除该角色？"
              onOk={() => handleDelete(record.id)}
            >
              <Button type="text" size="small" status="danger">
                删除
              </Button>
            </Popconfirm>
          </Permission>
        </Space>
      ),
    },
  ];

  return (
    <Card>
      <Space direction="vertical" style={{ width: '100%' }} size="large">
        <Space style={{ justifyContent: 'space-between', width: '100%' }}>
          <Typography.Title heading={4}>角色管理</Typography.Title>
          <Permission code="role:create">
            <Button type="primary" onClick={handleCreate}>
              创建角色
            </Button>
          </Permission>
        </Space>

        <Table
          rowKey="id"
          data={roles}
          columns={columns}
          loading={loading}
          pagination={false}
        />
      </Space>

      {/* 创建/编辑抽屉 */}
      <Drawer
        title={editingRole ? '编辑角色' : '创建角色'}
        visible={drawerVisible}
        onCancel={() => setDrawerVisible(false)}
        onOk={handleSave}
        // ponytail: confirmLoading replaced okLoading in newer Arco Design API
        confirmLoading={saving}
        width={560}
      >
        <Form layout="vertical">
          <Form.Item label="角色名称" required>
            <Input
              value={formValues.name}
              onChange={(v) => setFormValues({ ...formValues, name: v })}
              placeholder="请输入角色名称"
            />
          </Form.Item>
          <Form.Item label="描述">
            <Input.TextArea
              value={formValues.description}
              onChange={(v) => setFormValues({ ...formValues, description: v })}
              placeholder="请输入角色描述"
              autoSize={{ minRows: 2, maxRows: 4 }}
            />
          </Form.Item>
          <Form.Item label="权限配置">
            <Tree
              checkable
              treeData={treeData}
              checkedKeys={selectedPerms}
              onCheck={(keys) => setSelectedPerms(keys as string[])}
              // ponytail: defaultExpandAll removed in newer Arco Design, use defaultExpandedKeys instead
              defaultExpandedKeys={defaultExpandedKeys}
            />
          </Form.Item>
        </Form>
      </Drawer>
    </Card>
  );
}

/**
 * 将权限码列表按模块分组构建为树结构
 */
function buildPermTree(perms: PermissionItem[]): TreeNodeData[] {
  const groups: Record<string, TreeNodeData[]> = {};

  for (const perm of perms) {
    const prefix = perm.code.split(':')[0];
    const groupName = PERM_GROUPS[prefix] ?? prefix;

    if (!groups[groupName]) {
      groups[groupName] = [];
    }
    groups[groupName].push({
      key: perm.code,
      title: `${perm.name} (${perm.code})`,
    });
  }

  return Object.entries(groups).map(([groupName, children]) => ({
    key: `group:${groupName}`,
    title: groupName,
    children,
  }));
}
