import { useEffect, useState } from "react";
import {
  App as AntApp,
  Button,
  Card,
  Form,
  Input,
  Modal,
  Popconfirm,
  Space,
  Table,
  Tag,
  Typography,
} from "antd";
import { EditOutlined, PlusOutlined, ReloadOutlined, DeleteOutlined } from "@ant-design/icons";
import {
  Role,
  Session,
  createRole,
  deleteRole,
  getCompanyEntitlements,
  listRoles,
  updateRole,
} from "./api";
import { PermChecklist, permLabel } from "./agentPerms";
import { confirmCompanyWrite } from "./platformGuard";

type FormValues = {
  code?: string;
  name: string;
  description?: string;
  permissions: string[];
};

export function RolesPage(props: {
  session: Session;
  busy: boolean;
  setBusy: (v: boolean) => void;
  setError: (v: string) => void;
  setInfo: (v: string) => void;
}) {
  const { session, busy, setBusy, setError, setInfo } = props;
  const { message, modal } = AntApp.useApp();
  const [roles, setRoles] = useState<Role[]>([]);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<Role | null>(null);
  const [perms, setPerms] = useState<string[]>([]);
  const [allowedModules, setAllowedModules] = useState<
    { title: string; items?: { perm: string; desc: string }[]; perms?: string[] }[]
  >([]);
  const [form] = Form.useForm<FormValues>();

  async function refresh() {
    setLoading(true);
    try {
      const [res, ent] = await Promise.all([listRoles(session), getCompanyEntitlements(session)]);
      setRoles(res.items || []);
      setAllowedModules(ent.modules || []);
    } catch (e: any) {
      const msg = e.message || String(e);
      setError(msg);
      message.error(msg);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    refresh();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [session.accessToken, session.tenantId]);

  function openCreate() {
    setEditing(null);
    setPerms([]);
    form.resetFields();
    form.setFieldsValue({ permissions: [] });
    setOpen(true);
  }

  function openEdit(r: Role) {
    setEditing(r);
    setPerms([...(r.permissions || [])]);
    form.setFieldsValue({
      code: r.code,
      name: r.name,
      description: r.description,
      permissions: r.permissions || [],
    });
    setOpen(true);
  }

  async function onSubmit() {
    const values = await form.validateFields();
    if (!perms.length) {
      message.warning("请至少勾选一项权限");
      return;
    }
    const action = editing
      ? `保存智能体角色「${values.name.trim()}」及其权限`
      : `创建智能体角色「${values.name.trim()}」`;
    const ok = await confirmCompanyWrite(modal, session, action);
    if (!ok) return;
    setBusy(true);
    try {
      if (!editing) {
        await createRole(session, {
          code: (values.code || "").trim(),
          name: values.name.trim(),
          description: (values.description || "").trim(),
          permissions: perms,
        });
        message.success(`已创建角色「${values.name.trim()}」`);
        setInfo(`已创建角色「${values.name.trim()}」`);
      } else {
        await updateRole(session, editing.role_id, {
          name: values.name.trim(),
          description: (values.description || "").trim(),
          permissions: perms,
        });
        message.success(`已保存角色「${values.name.trim()}」`);
        setInfo(`已保存角色「${values.name.trim()}」`);
      }
      setOpen(false);
      await refresh();
    } catch (e: any) {
      const msg = e.message || String(e);
      setError(msg);
      message.error(msg);
    } finally {
      setBusy(false);
    }
  }

  return (
    <Card
      title="角色管理"
      extra={
        <Space>
          <Button icon={<ReloadOutlined />} onClick={refresh} loading={loading}>
            刷新
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
            新建角色
          </Button>
        </Space>
      }
    >
      <Typography.Paragraph type="secondary" style={{ marginTop: 0 }}>
        此处配置<strong>智能体角色</strong>。可选权限以平台超级管理员授予本公司的额度为准，无法勾选未授权项。
        默认角色：生成发布 / 只读 / 读写 / 运维。
      </Typography.Paragraph>

      <Table
        rowKey="role_id"
        loading={loading || busy}
        dataSource={roles}
        pagination={{ pageSize: 10 }}
        columns={[
          { title: "名称", dataIndex: "name", width: 140 },
          { title: "编码", dataIndex: "code", width: 140, render: (v) => <Tag>{v}</Tag> },
          { title: "说明", dataIndex: "description", ellipsis: true },
          {
            title: "权限",
            dataIndex: "permissions",
            render: (perms: string[]) =>
              (perms || []).length ? (
                <Space size={[4, 4]} wrap>
                  {(perms || []).slice(0, 8).map((p) => (
                    <Tag key={p}>{permLabel(p)}</Tag>
                  ))}
                  {(perms || []).length > 8 ? <Tag>+{(perms || []).length - 8}</Tag> : null}
                </Space>
              ) : (
                "—"
              ),
          },
          {
            title: "操作",
            width: 180,
            render: (_, r) => (
              <Space>
                <Button size="small" icon={<EditOutlined />} onClick={() => openEdit(r)}>
                  编辑
                </Button>
                <Popconfirm
                  title={`删除角色「${r.name}」？`}
                  onConfirm={async () => {
                    const ok = await confirmCompanyWrite(modal, session, `删除智能体角色「${r.name}」`);
                    if (!ok) return;
                    setBusy(true);
                    try {
                      await deleteRole(session, r.role_id);
                      message.success("已删除");
                      setInfo(`已删除角色「${r.name}」`);
                      await refresh();
                    } catch (e: any) {
                      message.error(e.message || String(e));
                      setError(e.message || String(e));
                    } finally {
                      setBusy(false);
                    }
                  }}
                >
                  <Button size="small" danger icon={<DeleteOutlined />}>
                    删除
                  </Button>
                </Popconfirm>
              </Space>
            ),
          },
        ]}
      />

      <Modal
        title={editing ? `编辑角色 #${editing.role_id}` : "新建角色"}
        open={open}
        onCancel={() => setOpen(false)}
        onOk={onSubmit}
        confirmLoading={busy}
        width={720}
        destroyOnClose
        okText="保存"
      >
        <Form form={form} layout="vertical" style={{ marginTop: 12 }}>
          <Form.Item
            label="角色编码"
            name="code"
            rules={editing ? [] : [{ required: true, message: "请填写中文编码，如 只读" }]}
          >
            <Input placeholder="如 只读 / 读写 / 自定义运维" disabled={!!editing} />
          </Form.Item>
          <Form.Item label="角色名称" name="name" rules={[{ required: true, message: "请填写名称" }]}>
            <Input placeholder="与编码可相同，如：只读" />
          </Form.Item>
          <Form.Item label="说明" name="description">
            <Input.TextArea rows={2} placeholder="可选" />
          </Form.Item>
          <Form.Item label="权限分配" required extra="仅显示本公司权限额度内的选项">
            <PermChecklist value={perms} onChange={setPerms} allowedModules={allowedModules} />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
}
