import { IMSDK } from "@/layout/MainContentWrap";
import { useContactStore } from "@/store";
import { feedbackToast } from "@/utils/common";
import { Input, Modal } from "antd";
import { useEffect, useState } from "react";

interface IAddColleagueProps {
  open: boolean;
  onClose: () => void;
}

/**
 * 添加同事弹窗（视觉规范 v1 §4.2）：
 * 工号输入 + 可编辑验证消息 + 发送按钮，五态：默认/校验失败/发送中/成功/失败。
 * 成功后刷新申请数，2s 后关闭并提示「申请已发送，等对方通过」。
 */
const AddColleague = ({ open, onClose }: IAddColleagueProps) => {
  const [staffNo, setStaffNo] = useState("");
  const [verifyMsg, setVerifyMsg] = useState("你好，我想加你为同事");
  const [error, setError] = useState("");
  const [sending, setSending] = useState(false);

  useEffect(() => {
    if (open) {
      setStaffNo("");
      setVerifyMsg("你好，我想加你为同事");
      setError("");
      setSending(false);
    }
  }, [open]);

  const send = async () => {
    const id = staffNo.trim();
    if (!id) {
      setError("请输入对方工号");
      return;
    }
    setSending(true);
    try {
      await IMSDK.addFriend({
        toUserID: id,
        reqMsg: verifyMsg.trim() || "你好，我想加你为同事",
      });
      useContactStore.getState().getRecvFriendApplicationListByReq();
      feedbackToast({ msg: "申请已发送，等对方通过" });
      setTimeout(onClose, 500);
    } catch (error) {
      setError("发送失败，请确认工号正确、网络正常");
      feedbackToast({ error, msg: "发送失败，请确认工号正确、网络正常" });
    } finally {
      setSending(false);
    }
  };

  return (
    <Modal
      title="添加同事"
      open={open}
      onCancel={sending ? undefined : onClose}
      footer={null}
      width={400}
      centered
      maskClosable={!sending}
      destroyOnClose
    >
      <div className="pt-2">
        <div className="mb-1.5 text-sm text-[var(--base-black)]">同事工号</div>
        <Input
          value={staffNo}
          onChange={(e) => {
            setStaffNo(e.target.value);
            if (error) setError("");
          }}
          placeholder="请输入对方工号"
          status={error ? "error" : undefined}
          style={{ height: 36, borderRadius: 8, backgroundColor: "var(--search-bg)" }}
          disabled={sending}
          onPressEnter={send}
        />
        {error && <div className="mt-1 text-xs text-[var(--warn-text)]">{error}</div>}
        <div className="mb-1.5 mt-4 text-sm text-[var(--base-black)]">验证消息（可不填）</div>
        <Input.TextArea
          value={verifyMsg}
          onChange={(e) => setVerifyMsg(e.target.value)}
          placeholder="你好，我想加你为同事"
          autoSize={{ minRows: 2, maxRows: 4 }}
          disabled={sending}
          style={{ borderRadius: 8, backgroundColor: "var(--search-bg)" }}
        />
        <button
          className="mt-5 flex h-9 w-full cursor-pointer items-center justify-center rounded-lg border-none bg-[var(--primary)] text-white disabled:cursor-not-allowed disabled:opacity-60"
          disabled={sending}
          onClick={send}
        >
          {sending ? <span className="h-4 w-4 animate-spin rounded-full border-2 border-white/40 border-t-white" /> : "发送申请"}
        </button>
      </div>
    </Modal>
  );
};

export default AddColleague;
