import { useEffect, useState } from "react";
import {
  App as AntApp,
  Button,
  Card,
  Form,
  Input,
  Modal,
  Select,
  Space,
  Table,
  Tag,
  Typography,
} from "antd";
import { PlusOutlined, ReloadOutlined } from "@ant-design/icons";
import {
  Member,
  OrgUnit,
  Session,
  createMember,
  listMembers,
  listOrgUnits,
  updateMember,
} from "./api";
import { roleLabel } from "./agentPerms";
import { confirmCompanyWrite } from "./platformGuard";

export function MembersPage(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 [items, setItems] = useState<Member[]>([]);
  const [orgs, setOrgs] = useState<OrgUnit[]>([]);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [phoneOpen, setPhoneOpen] = useState(false);
  const [phoneTarget, setPhoneTarget] = useState<Member | null>(null);
  const [phoneValue, setPhoneValue] = useState("");
  const [form] = Form.useForm<{
    password?: string;
    display_name?: string;
    role: string;
    org_unit_id?: number;
  }>();

  async function refresh() {
    setLoading(true);
    try {
      const [m, o] = await Promise.all([
        listMembers(session),
        listOrgUnits(session).catch(() => ({ items: [] as OrgUnit[] })),
      ]);
      setItems(m.items || []);
      setOrgs(o.items || []);
    } catch (e: any) {
      const msg = e.message || String(e);
      setError(msg);
      message.error(msg);
    } finally {
      setLoading(false);
    }
  }

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

  async function patchMember(
    r: Member,
    action: string,
    body: { role?: string; org_unit_id?: number; status?: string }
  ) {
    const ok = await confirmCompanyWrite(
      modal,
      session,
      action,
      `成员：${r.display_name || r.username}（#${r.user_id}）`
    );
    if (!ok) return;
    setBusy(true);
    try {
      await updateMember(session, r.user_id, body);
      setInfo(`${action}成功`);
      await refresh();
    } catch (e: any) {
      message.error(e.message || String(e));
    } finally {
      setBusy(false);
    }
  }

  return (
    <Card
      title="成员管理"
      extra={
        <Space>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              form.setFieldsValue({
                role: "编辑",
                password: undefined,
                display_name: undefined,
                org_unit_id: undefined,
              });
              setOpen(true);
            }}
          >
            新建成员
          </Button>
          <Button icon={<ReloadOutlined />} onClick={() => void refresh()} loading={loading}>
            刷新
          </Button>
        </Space>
      }
    >
      <Typography.Paragraph type="secondary" style={{ marginTop: 0 }}>
        用户名由系统随机生成且全局唯一；初始密码可留空自动生成，登录后可自行「修改密码」。也可走「邀请加入」。
        管理员可为成员「绑定手机」（登录/同号同步联调用）；顶栏「更换手机」只改当前登录账号。
        {session.role === "超级管理员" || session.role === "platform_admin"
          ? " 超管代管修改时会要求两次确认。"
          : ""}
      </Typography.Paragraph>
      <Table
        rowKey="user_id"
        loading={loading || busy}
        dataSource={items}
        pagination={{ pageSize: 10 }}
        columns={[
          { title: "用户名", dataIndex: "username", width: 140 },
          {
            title: "手机号",
            dataIndex: "phone",
            width: 200,
            render: (v: string, r: Member) => (
              <Space size={4}>
                {v ? (
                  <Typography.Text copyable>{v}</Typography.Text>
                ) : (
                  <Typography.Text type="secondary">未绑定</Typography.Text>
                )}
                <Button
                  type="link"
                  size="small"
                  style={{ padding: 0 }}
                  onClick={() => {
                    setPhoneTarget(r);
                    setPhoneValue(v || "");
                    setPhoneOpen(true);
                  }}
                >
                  {v ? "更换" : "绑定"}
                </Button>
              </Space>
            ),
          },
          { title: "显示名", dataIndex: "display_name", width: 120 },
          {
            title: "角色",
            dataIndex: "role",
            width: 160,
            render: (role: string, r: Member) => (
              <Select
                size="small"
                style={{ width: 120 }}
                value={role}
                disabled={r.user_id === session.userId}
                options={[
                  { value: "管理员", label: "管理员" },
                  { value: "编辑", label: "编辑" },
                  { value: "只读", label: "只读" },
                ]}
                onChange={(v) => void patchMember(r, `将 ${r.username} 设为${roleLabel(v)}`, { role: v })}
              />
            ),
          },
          {
            title: "组织",
            width: 160,
            render: (_: unknown, r: Member) => (
              <Select
                size="small"
                allowClear
                style={{ width: 140 }}
                placeholder="全公司"
                value={r.org_unit_id || undefined}
                options={orgs.map((o) => ({ value: o.org_unit_id, label: o.name }))}
                onChange={(v) =>
                  void patchMember(r, `调整 ${r.username} 的组织`, { org_unit_id: v || 0 })
                }
              />
            ),
          },
          {
            title: "状态",
            dataIndex: "status",
            width: 120,
            render: (st: string, r: Member) => (
              <Select
                size="small"
                style={{ width: 100 }}
                value={st || "active"}
                disabled={r.user_id === session.userId}
                options={[
                  { value: "active", label: "正常" },
                  { value: "disabled", label: "停用" },
                ]}
                onChange={(v) =>
                  void patchMember(r, `${v === "disabled" ? "停用" : "启用"}成员 ${r.username}`, {
                    status: v,
                  })
                }
              />
            ),
          },
          {
            title: "角色标签",
            width: 90,
            render: (_: unknown, r: Member) => <Tag>{roleLabel(r.role)}</Tag>,
          },
        ]}
      />

      <Modal
        title={phoneTarget?.phone ? "更换手机号" : "绑定手机号"}
        open={phoneOpen}
        onCancel={() => {
          setPhoneOpen(false);
          setPhoneTarget(null);
        }}
        onOk={async () => {
          if (!phoneTarget) return;
          const trimmed = phoneValue.trim();
          const ok = await confirmCompanyWrite(
            modal,
            session,
            trimmed ? "绑定/更换成员手机号" : "解绑成员手机号",
            `成员：${phoneTarget.display_name || phoneTarget.username}（#${phoneTarget.user_id}）→ ${trimmed || "（空）"}`
          );
          if (!ok) return;
          setBusy(true);
          try {
            await updateMember(session, phoneTarget.user_id, { phone: trimmed });
            setInfo(trimmed ? `已绑定 ${trimmed}` : "已解绑手机号");
            setPhoneOpen(false);
            setPhoneTarget(null);
            await refresh();
          } catch (e: any) {
            message.error(e.message || String(e));
          } finally {
            setBusy(false);
          }
        }}
        confirmLoading={busy}
        destroyOnHidden
        okText="保存"
      >
        <Typography.Paragraph type="secondary">
          用于手机号登录与松离线同号绑定联调。生产宇信达请绑{" "}
          <Typography.Text code>13531041944</Typography.Text>
          ；勿绑超管号 13531041945。清空并保存即解绑。
        </Typography.Paragraph>
        <Input
          value={phoneValue}
          onChange={(e) => setPhoneValue(e.target.value)}
          placeholder="例：13531041944"
          maxLength={20}
          allowClear
        />
      </Modal>

      <Modal
        title="新建成员"
        open={open}
        onCancel={() => setOpen(false)}
        onOk={async () => {
          const v = await form.validateFields();
          const ok = await confirmCompanyWrite(
            modal,
            session,
            "新建成员",
            "将随机生成唯一用户名；初始密码可稍后由本人修改"
          );
          if (!ok) return;
          setBusy(true);
          try {
            const res = await createMember(session, {
              password: (v.password || "").trim(),
              display_name: (v.display_name || "").trim(),
              role: v.role,
              org_unit_id: v.org_unit_id || 0,
            });
            modal.info({
              title: "成员已创建 — 请保存账号",
              content: (
                <div>
                  <p>
                    用户名：<Typography.Text copyable code>{res.username}</Typography.Text>
                  </p>
                  <p>
                    初始密码：<Typography.Text copyable code>{res.password}</Typography.Text>
                  </p>
                  <p>角色：{roleLabel(res.role)}</p>
                  <Typography.Text type="secondary">
                    用户名随机唯一不可改；密码请交给本人后由其登录并自行修改。
                  </Typography.Text>
                </div>
              ),
              okText: "已保存",
            });
            setInfo(`已创建成员 ${res.username}`);
            setOpen(false);
            form.resetFields();
            await refresh();
          } catch (e: any) {
            message.error(e.message || String(e));
          } finally {
            setBusy(false);
          }
        }}
        confirmLoading={busy}
        destroyOnHidden
      >
        <Form form={form} layout="vertical" initialValues={{ role: "编辑" }}>
          <Typography.Paragraph type="secondary">
            用户名由系统随机生成（全局唯一）。初始密码可指定，留空则随机生成；登录后可自行修改。
          </Typography.Paragraph>
          <Form.Item name="password" label="初始密码" extra="留空则随机生成">
            <Input.Password placeholder="至少 6 位，可留空" />
          </Form.Item>
          <Form.Item name="display_name" label="显示名">
            <Input placeholder="可选" />
          </Form.Item>
          <Form.Item name="role" label="角色" rules={[{ required: true }]}>
            <Select
              options={[
                { value: "管理员", label: "管理员（公司顶级）" },
                { value: "编辑", label: "编辑" },
                { value: "只读", label: "只读" },
              ]}
            />
          </Form.Item>
          <Form.Item name="org_unit_id" label="组织">
            <Select
              allowClear
              placeholder="全公司（不限组织）"
              options={orgs.map((o) => ({ value: o.org_unit_id, label: o.name }))}
            />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
}
