import { Checkbox, Space, Typography } from "antd";

/** 权限统一中文命名（与平台 authx 一致；英文旧码写入时会被后端归一） */
export const AGENT_PERM_GROUPS: { title: string; items: { id: string; label: string }[] }[] = [
  {
    title: "模块",
    items: [
      { id: "读取模块", label: "读取模块" },
      { id: "写入模块", label: "写入模块" },
      { id: "发布模块", label: "发布模块" },
    ],
  },
  {
    title: "数据",
    items: [
      { id: "查询数据", label: "查询数据" },
      { id: "新增数据", label: "新增数据" },
      { id: "更新数据", label: "更新数据" },
      { id: "删除数据", label: "删除数据" },
      { id: "导入数据", label: "导入数据" },
      { id: "导出数据", label: "导出数据" },
    ],
  },
  {
    title: "其他",
    items: [
      { id: "下载文件", label: "下载文件" },
      { id: "上传文件", label: "上传文件" },
      { id: "查看审计", label: "查看审计" },
    ],
  },
];

/** 英文旧码 → 中文（列表展示兼容历史数据） */
const LEGACY_PERM: Record<string, string> = {
  "app.read": "读取模块",
  "app.write": "写入模块",
  "app.admin": "发布模块",
  "row.create": "新增数据",
  "row.read": "查询数据",
  "row.update": "更新数据",
  "row.delete": "删除数据",
  "row.export": "导出数据",
  "row.import": "导入数据",
  "audit.read": "查看审计",
  "storage.write": "上传文件",
  "storage.read": "下载文件",
  "agent.admin": "管理智能体",
  "tenant.invite": "邀请成员",
  "org.admin": "管理组织",
  "sync.admin": "数据同步",
};

const PERM_LABEL: Record<string, string> = {
  ...Object.fromEntries(AGENT_PERM_GROUPS.flatMap((g) => g.items.map((i) => [i.id, i.label]))),
  管理智能体: "管理智能体",
  邀请成员: "邀请成员",
  管理组织: "管理组织",
  数据同步: "数据同步",
};

/** 权限码 → 中文显示名 */
export function permLabel(code: string): string {
  const n = LEGACY_PERM[code] || code;
  return PERM_LABEL[n] || n;
}

/** 平台成员角色归一（兼容英文旧码） */
export function normalizeRole(role: string): string {
  switch (role) {
    case "platform_admin":
    case "super_admin":
    case "超级管理员":
      return "超级管理员";
    case "owner":
    case "管理员":
      return "管理员";
    case "editor":
    case "编辑":
      return "编辑";
    case "viewer":
    case "只读":
      return "只读";
    case "pending":
    case "待加入":
      return "待加入";
    case "agent":
    case "智能体":
      return "智能体";
    default:
      return role;
  }
}

export function roleLabel(role: string): string {
  return normalizeRole(role);
}

export function isPlatformAdmin(role?: string): boolean {
  return normalizeRole(role || "") === "超级管理员";
}

export function isOwner(role?: string): boolean {
  return normalizeRole(role || "") === "管理员";
}

/** 公司管理功能：仅公司管理员（超级管理员不管公司内部） */
export function isCompanyAdmin(role?: string): boolean {
  return normalizeRole(role || "") === "管理员";
}

export function isPendingRole(role?: string): boolean {
  return normalizeRole(role || "") === "待加入";
}

/** 智能体角色编码归一 */
export function normalizeAgentRoleCode(code: string): string {
  switch (code) {
    case "publisher":
    case "生成发布":
      return "生成发布";
    case "viewer":
    case "只读":
      return "只读";
    case "editor":
    case "读写":
      return "读写";
    case "operator":
    case "运维":
      return "运维";
    default:
      return code;
  }
}

export function PermChecklist(props: {
  value: string[];
  onChange: (next: string[]) => void;
  /** 若传入，则只展示公司额度内的权限模块（含说明） */
  allowedModules?: { title: string; items?: { perm: string; desc: string }[]; perms?: string[] }[];
}) {
  const groups = (props.allowedModules?.length
    ? props.allowedModules
    : AGENT_PERM_GROUPS.map((g) => ({
        title: g.title,
        items: g.items.map((i) => ({ perm: i.id, desc: i.label })),
      }))
  ).map((g: { title: string; items?: { perm: string; desc: string }[]; perms?: string[] }) => ({
    title: g.title,
    items:
      g.items ||
      (g.perms || []).map((p: string) => ({ perm: p, desc: permLabel(p) })),
  }));
  const normalized = props.value.map((p) => LEGACY_PERM[p] || p);
  return (
    <Space direction="vertical" size="middle" style={{ width: "100%" }}>
      {groups.map((g) => {
        const groupPerms = g.items.map((i: { perm: string; desc: string }) => i.perm);
        return (
          <div key={g.title}>
            <Typography.Text type="secondary" strong>
              {g.title}
            </Typography.Text>
            <div style={{ marginTop: 8 }}>
              <Checkbox.Group
                style={{
                  width: "100%",
                  display: "grid",
                  gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))",
                  gap: 8,
                }}
                value={normalized.filter((p) => groupPerms.includes(p))}
                onChange={(checked) => {
                  const groupIds = new Set(groupPerms);
                  const kept = normalized.filter((p) => !groupIds.has(p));
                  props.onChange([...kept, ...(checked as string[])]);
                }}
                options={g.items.map((i: { perm: string; desc: string }) => ({
                  label: (
                    <span>
                      {permLabel(i.perm)}
                      {i.desc ? (
                        <>
                          <br />
                          <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                            {i.desc}
                          </Typography.Text>
                        </>
                      ) : null}
                    </span>
                  ),
                  value: i.perm,
                }))}
              />
            </div>
          </div>
        );
      })}
    </Space>
  );
}

export function hasEntitlement(perms: string[] | null | undefined, need: string): boolean {
  // null = 尚未加载，先按有权限展示，避免闪空
  if (perms == null) return true;
  return perms.includes(need);
}
