import { useEffect, useState } from "react";
import {
  App as AntApp,
  Button,
  Card,
  Form,
  InputNumber,
  Modal,
  Popconfirm,
  Select,
  Space,
  Table,
  Tag,
  Typography,
} from "antd";
import { PlusOutlined, ReloadOutlined, StopOutlined } from "@ant-design/icons";
import {
  OrgUnit,
  Session,
  TenantInvite,
  createInvite,
  listInvites,
  listOrgUnits,
  revokeInvite,
} from "./api";
import { roleLabel } from "./agentPerms";

export function InvitesPage(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 } = AntApp.useApp();
  const [items, setItems] = useState<TenantInvite[]>([]);
  const [orgs, setOrgs] = useState<OrgUnit[]>([]);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm<{ role: string; org_unit_id?: number; max_uses: number; expires_in_hours?: number }>();

  async function refresh() {
    setLoading(true);
    try {
      const [inv, ou] = await Promise.all([listInvites(session), listOrgUnits(session).catch(() => ({ items: [] as OrgUnit[] }))]);
      setItems(inv.items || []);
      setOrgs(ou.items || []);
    } 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]);

  async function onCreate() {
    const values = await form.validateFields();
    setBusy(true);
    try {
      const inv = await createInvite(session, {
        role: values.role,
        org_unit_id: values.org_unit_id || 0,
        max_uses: values.max_uses,
        expires_in_hours: values.expires_in_hours || 0,
      });
      message.success(`邀请码已创建：${inv.code}`);
      setInfo(`邀请码 ${inv.code}（角色 ${inv.role}）`);
      setOpen(false);
      await refresh();
    } catch (e: any) {
      message.error(e.message || String(e));
      setError(e.message || String(e));
    } finally {
      setBusy(false);
    }
  }

  return (
    <Card
      title="邀请加入"
      extra={
        <Space>
          <Button icon={<ReloadOutlined />} onClick={refresh} loading={loading}>
            刷新
          </Button>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              form.setFieldsValue({ role: "编辑", max_uses: 1, expires_in_hours: 72, org_unit_id: undefined });
              setOpen(true);
            }}
          >
            生成邀请码
          </Button>
        </Space>
      }
    >
      <Typography.Paragraph type="secondary" style={{ marginTop: 0 }}>
        把邀请码发给新用户。对方注册后处于「待加入」，输入邀请码即可成为本司成员。
        成员角色：<strong>管理员</strong>（顶级，含数据同步）、<strong>编辑</strong>（读写数据）、
        <strong>只读</strong>（仅查看导出）。详见 docs/角色说明.md。
      </Typography.Paragraph>

      <Table
        rowKey="invite_id"
        loading={loading || busy}
        dataSource={items}
        pagination={{ pageSize: 10 }}
        columns={[
          {
            title: "邀请码",
            dataIndex: "code",
            render: (v) => (
              <Typography.Text copyable code>
                {v}
              </Typography.Text>
            ),
          },
          { title: "加入角色", dataIndex: "role", width: 100, render: (v: string) => <Tag>{roleLabel(v)}</Tag> },
          {
            title: "组织",
            width: 140,
            render: (_, r) => {
              if (!r.org_unit_id) return "全公司";
              const o = orgs.find((x) => x.org_unit_id === r.org_unit_id);
              return o?.name || `#${r.org_unit_id}`;
            },
          },
          {
            title: "使用",
            width: 100,
            render: (_, r) => `${r.used_count}/${r.max_uses}`,
          },
          {
            title: "状态",
            dataIndex: "status",
            width: 110,
            render: (v) => {
              if (v === "active") return <Tag color="success">有效</Tag>;
              if (v === "revoked") return <Tag>已撤销</Tag>;
              if (v === "exhausted") return <Tag color="warning">已用尽</Tag>;
              return <Tag>{v}</Tag>;
            },
          },
          {
            title: "过期",
            dataIndex: "expires_at",
            render: (v) => (v ? new Date(v).toLocaleString() : "不过期"),
          },
          {
            title: "操作",
            width: 120,
            render: (_, r) =>
              r.status === "active" ? (
                <Popconfirm
                  title="撤销该邀请码？"
                  onConfirm={async () => {
                    setBusy(true);
                    try {
                      await revokeInvite(session, r.invite_id);
                      message.success("已撤销");
                      await refresh();
                    } catch (e: any) {
                      message.error(e.message || String(e));
                    } finally {
                      setBusy(false);
                    }
                  }}
                >
                  <Button size="small" danger icon={<StopOutlined />}>
                    撤销
                  </Button>
                </Popconfirm>
              ) : (
                "—"
              ),
          },
        ]}
      />

      <Modal
        title="生成邀请码"
        open={open}
        onCancel={() => setOpen(false)}
        onOk={onCreate}
        confirmLoading={busy}
        okText="生成"
        destroyOnClose
      >
        <Form form={form} layout="vertical" style={{ marginTop: 12 }}>
          <Form.Item label="加入后角色" name="role" rules={[{ required: true }]}>
            <Select
              options={[
                { value: "编辑", label: "编辑 — 可读写业务数据，不可发布/管组织" },
                { value: "只读", label: "只读 — 仅查看与导出" },
                { value: "管理员", label: "管理员 — 公司顶级（含数据同步）" },
              ]}
            />
          </Form.Item>
          <Form.Item label="绑定组织（可选）" name="org_unit_id">
            <Select
              allowClear
              placeholder="空=不绑组织（可见全公司数据）"
              options={orgs.map((o) => ({
                value: o.org_unit_id,
                label: `${"— ".repeat(Math.max(0, o.depth - 1))}${o.name}`,
              }))}
            />
          </Form.Item>
          <Form.Item label="可用次数" name="max_uses" rules={[{ required: true }]}>
            <InputNumber min={1} max={1000} style={{ width: "100%" }} />
          </Form.Item>
          <Form.Item label="有效小时数（0=不过期）" name="expires_in_hours">
            <InputNumber min={0} max={8760} style={{ width: "100%" }} />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
}
