const { useState } = React;
const { Icon, ProtoNav, Topbar, Sidebar, Footer } = window;

// 模拟数据：包含用户提交的完整三块信息
const MOCK_USERS = [
  {
    id: 1, email: "user1@example.com", phone: "+86 138****1234", company: "A公司", state: "LEAD_APPLIED",
    regTime: "2026-05-20 14:30", lastLogin: "—", source: "展会",
    salesEmail: "",
    // ① 基本信息
    basicInfo: {
      companyName: "A科技有限公司", country: "中国", city: "深圳",
      contactName: "张三", contactPhone: "+86 13800138000", contactEmail: "zhang@atech.com"
    },
    // ② 业务信息
    businessInfo: {
      useCase: "智能摘要", useCaseDesc: "市场部使用大模型自动生成产品文档摘要，提升内容产出效率。",
      requirementBackground: "公司主营云计算服务，需要快速生成技术文档摘要供客户阅读。",
      modelName: "GPT-4o"
    },
    // ③ 客户经理信息
    managerInfo: {
      managerName: "", managerEmail: ""
    },
    // EB / iBOSS 信息（可折叠）
    ebInfo: { status: "待审批", opportunityId: "", projectAmount: "", signDate: "" },
    ibossInfo: { status: "未开始", industry: "", companyCode: "", businessLocation: "", companyAddress: "" }
  },
  {
    id: 2, email: "user2@example.com", phone: "+86 139****5678", company: "B公司", state: "LEAD_APPROVED",
    regTime: "2026-04-15 10:00", lastLogin: "2026-06-16 18:30", source: "销售推荐",
    salesEmail: "sales@cmi.com",
    basicInfo: {
      companyName: "B国际贸易有限公司", country: "中国香港", city: "香港",
      contactName: "李四", contactPhone: "+852 91234567", contactEmail: "li@btrade.hk"
    },
    businessInfo: {
      useCase: "文档解析", useCaseDesc: "法务部门使用大模型解析合同文档，提取关键条款。",
      requirementBackground: "每月处理数百份国际贸易合同，需要自动化提取关键信息。",
      modelName: "Claude"
    },
    managerInfo: {
      managerName: "王经理", managerEmail: "wang@cmi.com"
    },
    ebInfo: { status: "已通过", opportunityId: "OPP-2026-001", projectAmount: "50000", signDate: "2026-07-01" },
    ibossInfo: { status: "已通过", industry: "贸易", companyCode: "91440300MA5G8KXXXX", businessLocation: "香港", companyAddress: "香港中环XX大厦" }
  },
  {
    id: 3, email: "user3@example.com", phone: "+86 137****9012", company: "C公司", state: "VERIFIED",
    regTime: "2026-05-28 16:45", lastLogin: "2026-06-15 11:20", source: "自来",
    salesEmail: "",
    basicInfo: {
      companyName: "C金融科技公司", country: "新加坡", city: "新加坡",
      contactName: "陈五", contactPhone: "+65 81234567", contactEmail: "chen@cfintech.sg"
    },
    businessInfo: {
      useCase: "风险识别", useCaseDesc: "风控部门使用大模型分析交易数据，识别潜在欺诈风险。",
      requirementBackground: "需要实时分析海量交易数据，提升风险识别准确率。",
      modelName: ""
    },
    managerInfo: {
      managerName: "", managerEmail: ""
    },
    ebInfo: { status: "已通过", opportunityId: "OPP-2026-003", projectAmount: "120000", signDate: "2026-08-15" },
    ibossInfo: { status: "已通过", industry: "金融", companyCode: "", businessLocation: "", companyAddress: "" }
  },
  {
    id: 4, email: "user4@example.com", phone: "+86 136****3456", company: "D公司", state: "LEAD_APPLIED",
    regTime: "2026-06-10 09:00", lastLogin: "—", source: "其他",
    salesEmail: "",
    basicInfo: {
      companyName: "D教育科技有限公司", country: "中国", city: "北京",
      contactName: "赵六", contactPhone: "+86 13600136000", contactEmail: "zhao@dedu.com"
    },
    businessInfo: {
      useCase: "智能问答", useCaseDesc: "客服部门使用大模型构建智能问答系统，解答学生咨询。",
      requirementBackground: "日均咨询量超过5000条，需要7×24小时自动回复。",
      modelName: "GLM-4"
    },
    managerInfo: {
      managerName: "", managerEmail: ""
    },
    ebInfo: { status: "待审批", opportunityId: "", projectAmount: "", signDate: "" },
    ibossInfo: { status: "未开始", industry: "", companyCode: "", businessLocation: "", companyAddress: "" }
  },
  {
    id: 5, email: "user5@example.com", phone: "+86 135****7890", company: "E公司", state: "EB_APPROVED",
    regTime: "2026-03-20 08:30", lastLogin: "2026-06-17 07:45", source: "展会",
    salesEmail: "li@cmi.com",
    basicInfo: {
      companyName: "E制造集团有限公司", country: "中国", city: "上海",
      contactName: "孙七", contactPhone: "+86 13500135000", contactEmail: "sun@emfg.com"
    },
    businessInfo: {
      useCase: "数据提取", useCaseDesc: "生产部门使用大模型从设备日志中提取故障信息。",
      requirementBackground: "工厂设备数量庞大，需要自动化分析设备日志。",
      modelName: "文心"
    },
    managerInfo: {
      managerName: "周经理", managerEmail: "zhou@cmi.com"
    },
    ebInfo: { status: "已通过", opportunityId: "OPP-2026-005", projectAmount: "80000", signDate: "2026-09-01" },
    ibossInfo: { status: "已通过", industry: "制造", companyCode: "91310000MA5FLXXXX", businessLocation: "上海", companyAddress: "上海浦东新区XX路" }
  },
];

const STATE_META = {
  LEAD_APPLIED:  { label: "审核中", tone: "warning" },
  LEAD_APPROVED: { label: "试用中", tone: "info" },
  EB_APPROVED:   { label: "EB通过", tone: "info" },
  VERIFIED:      { label: "待订购", tone: "info" },
  SUBSCRIBED:    { label: "已订购", tone: "success" },
  LEAD_REJECTED: { label: "已驳回", tone: "error" },
  EB_REJECTED:   { label: "EB驳回", tone: "error" },
};

function StateTag({ state }) {
  const meta = STATE_META[state] || { label: state, tone: "neutral" };
  return <span className={"tag tag--" + meta.tone}>{meta.label}</span>;
}

// =====================================================================
// DICT 审核工作台弹窗 (600px)
// =====================================================================
function UserDetailModal({ user, onClose, onApprove, onReject, onSendReminder }) {
  const [salesEmail, setSalesEmail] = useState(user.salesEmail);
  const [followUp, setFollowUp] = useState("");
  const [records, setRecords] = useState([
    { time: user.regTime, text: "用户提交留资申请" },
  ]);
  const [error, setError] = useState("");
  const [ebOpen, setEbOpen] = useState(false);
  const [ibossOpen, setIbossOpen] = useState(false);

  const isPending = user.state === "LEAD_APPLIED";

  const addRecord = () => {
    if (!followUp.trim()) return;
    setRecords([...records, { time: new Date().toLocaleString("zh-CN"), text: followUp }]);
    setFollowUp("");
  };

  const handleApprove = () => {
    if (!salesEmail.trim()) {
      setError("审核通过前必须填写负责跟进的销售邮箱");
      return;
    }
    setError("");
    onApprove({ ...user, salesEmail });
  };

  const handleReject = () => {
    if (!window.confirm("确认驳回？驳回后用户仍看到审核中，不可重新提交。")) return;
    onReject(user);
  };

  const handleSendReminder = () => {
    if (!salesEmail.trim()) {
      alert("请填写销售邮箱");
      return;
    }
    onSendReminder({ userId: user.id, salesEmail });
  };

  // 信息展示行
  const InfoRow = ({ label, value }) => (
    <div className="detail-row">
      <span className="detail-label">{label}</span>
      <span className="detail-value">{value || "—"}</span>
    </div>
  );

  // 折叠触发器
  const CollapseTrigger = ({ open, onClick, title, badge }) => (
    <button className={"iboss-collapse-trigger" + (open ? " iboss-collapse-trigger--open" : "")} onClick={onClick}>
      <Icon.ChevronRight size={18} className="iboss-collapse-icon" />
      <span className="iboss-collapse-title">{title}</span>
      {badge && <span className="iboss-collapse-badge">{badge}</span>}
    </button>
  );

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal modal--md" onClick={e => e.stopPropagation()} data-screen-label="user-detail-modal">
        <div className="modal-header">
          <div>
            <h3 className="modal-title">用户审核详情</h3>
            <p className="modal-subtitle">DICT 审核工作台 · {user.company}</p>
          </div>
          <button className="modal-close" onClick={onClose}><Icon.Close size={18} /></button>
        </div>
        <div className="modal-body">
          {/* 用户基本信息 */}
          <div className="detail-section">
            <InfoRow label="邮箱" value={user.email} />
            <InfoRow label="手机号" value={user.phone} />
            <InfoRow label="企业名" value={user.company} />
            <InfoRow label="注册时间" value={user.regTime} />
            <InfoRow label="当前状态" value={<StateTag state={user.state} />} />
            <InfoRow label="来源" value={user.source} />
          </div>

          {/* ① 基本信息 */}
          <div className="detail-section">
            <h4 className="detail-section-title"><Icon.Building size={16} /> ① 基本信息</h4>
            <InfoRow label="企业注册名称" value={user.basicInfo.companyName} />
            <InfoRow label="国家/地区" value={user.basicInfo.country} />
            <InfoRow label="城市" value={user.basicInfo.city} />
            <InfoRow label="联系人姓名" value={user.basicInfo.contactName} />
            <InfoRow label="联系人电话" value={user.basicInfo.contactPhone} />
            <InfoRow label="联系人邮箱" value={user.basicInfo.contactEmail} />
          </div>

          {/* ② 业务信息 */}
          <div className="detail-section">
            <h4 className="detail-section-title"><Icon.Sparkles size={16} /> ② 业务信息</h4>
            <InfoRow label="应用场景" value={user.businessInfo.useCase} />
            <InfoRow label="场景描述" value={user.businessInfo.useCaseDesc} />
            <InfoRow label="需求背景" value={user.businessInfo.requirementBackground} />
            <InfoRow label="模型名称" value={user.businessInfo.modelName} />
          </div>

          {/* ③ 客户经理信息 */}
          <div className="detail-section">
            <h4 className="detail-section-title"><Icon.Headset size={16} /> ③ 客户经理信息</h4>
            <InfoRow label="客户经理姓名" value={user.managerInfo.managerName} />
            <InfoRow label="客户经理邮箱" value={user.managerInfo.managerEmail} />
          </div>

          {/* EB 审核信息（可折叠） */}
          <CollapseTrigger
            open={ebOpen}
            onClick={() => setEbOpen(!ebOpen)}
            title="EB 审核信息"
            badge={user.ebInfo.status}
          />
          {ebOpen && (
            <div className="iboss-collapse-content">
              <InfoRow label="审核状态" value={user.ebInfo.status} />
              <InfoRow label="Opportunity ID" value={user.ebInfo.opportunityId} />
              <InfoRow label="预计项目金额" value={user.ebInfo.projectAmount ? "$" + user.ebInfo.projectAmount : ""} />
              <InfoRow label="预计签约时间" value={user.ebInfo.signDate} />
            </div>
          )}

          {/* iBOSS 认证信息（可折叠） */}
          <CollapseTrigger
            open={ibossOpen}
            onClick={() => setIbossOpen(!ibossOpen)}
            title="iBOSS 认证信息"
            badge={user.ibossInfo.status}
          />
          {ibossOpen && (
            <div className="iboss-collapse-content">
              <InfoRow label="认证状态" value={user.ibossInfo.status} />
              <InfoRow label="行业" value={user.ibossInfo.industry} />
              <InfoRow label="企业注册编码" value={user.ibossInfo.companyCode} />
              <InfoRow label="业务拓展地" value={user.ibossInfo.businessLocation} />
              <InfoRow label="公司地址" value={user.ibossInfo.companyAddress} />
            </div>
          )}

          {/* 销售邮箱 */}
          <div className="detail-section">
            <label className="detail-field-label">
              跟进销售邮箱
              {isPending && <span className="detail-required">（必填，审核通过前）</span>}
            </label>
            <input
              className="input"
              placeholder="请输入销售邮箱"
              value={salesEmail}
              onChange={e => { setSalesEmail(e.target.value); setError(""); }}
              disabled={!isPending}
            />
            {error && <span className="detail-error">{error}</span>}
          </div>

          {/* 跟进记录 */}
          <div className="detail-section">
            <label className="detail-field-label">跟进记录</label>
            <div className="detail-records">
              {records.map((r, i) => (
                <div key={i} className="detail-record">
                  <span className="detail-record-time">{r.time}</span>
                  <span className="detail-record-text">{r.text}</span>
                </div>
              ))}
            </div>
            <div className="detail-record-input">
              <textarea
                className="textarea"
                placeholder="记录联系情况和跟进状态"
                value={followUp}
                onChange={e => setFollowUp(e.target.value)}
                rows={2}
              />
              <button className="btn btn--secondary btn--sm" onClick={addRecord}>追加记录</button>
            </div>
          </div>
        </div>
        <div className="modal-footer">
          {isPending ? (
            <>
              <button className="btn btn--danger" onClick={handleReject}>驳回</button>
              <div className="modal-footer-spacer" />
              <button className="btn btn--secondary" onClick={handleSendReminder}>发送跟进邮件</button>
              <button className="btn btn--primary" onClick={handleApprove}>审核通过</button>
            </>
          ) : (
            <>
              <button className="btn btn--secondary" onClick={onClose}>关闭</button>
              <div className="modal-footer-spacer" />
              <button className="btn btn--primary" onClick={handleSendReminder}>发送跟进邮件</button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// =====================================================================
// 主页面
// =====================================================================
function UserQuery() {
  const [keyword, setKeyword] = useState("");
  const [filterState, setFilterState] = useState("ALL");
  const [detailUser, setDetailUser] = useState(null);
  const [users, setUsers] = useState(MOCK_USERS);

  const filtered = users.filter(u => {
    if (filterState !== "ALL" && u.state !== filterState) return false;
    if (keyword && !u.email.includes(keyword) && !u.company.includes(keyword) && !u.phone.includes(keyword)) return false;
    return true;
  });

  const handleApprove = (updatedUser) => {
    setUsers(users.map(u => u.id === updatedUser.id ? { ...u, ...updatedUser, state: "LEAD_APPROVED" } : u));
    alert(`审核通过！已发送邮件至 ${updatedUser.salesEmail}`);
    setDetailUser(null);
  };

  const handleReject = (user) => {
    setUsers(users.map(u => u.id === user.id ? { ...u, state: "LEAD_REJECTED" } : u));
    setDetailUser(null);
  };

  const handleSendReminder = ({ userId, salesEmail }) => {
    alert(`跟进提醒已发送至 ${salesEmail}`);
    if (detailUser && detailUser.id === userId) {
      // 保持弹窗打开，仅提示
    }
  };

  return (
    <div className="proto-root">
      <ProtoNav active="admin-user" />
      <div className="app-shell">
        <Sidebar active="user-query" showAdmin={true} />
        <div className="app-main">
          <Topbar crumbs={[{ label: "运营管理", href: "#" }, { label: "用户查询" }]} state="SUBSCRIBED" balance={200} />
          <main className="app-content" data-screen-label="admin-user-query">
            <div className="admin-page">
              <div className="admin-header" data-region="admin-user-header">
                <h1 className="admin-title">用户查询</h1>
                <p className="admin-sub">运营管理 / 用户查询 · DICT 审核工作台</p>
              </div>

              <div className="filter-bar" data-region="admin-user-filter">
                <div className="filter-fields">
                  <div className="filter-field">
                    <label>状态</label>
                    <select className="select select--sm" value={filterState} onChange={e => setFilterState(e.target.value)}>
                      <option value="ALL">全部</option>
                      {Object.keys(STATE_META).map(s => <option key={s} value={s}>{STATE_META[s].label}</option>)}
                    </select>
                  </div>
                  <div className="filter-field filter-field--grow">
                    <label>关键词</label>
                    <input className="input input--sm" placeholder="邮箱 / 手机号 / 企业名" value={keyword} onChange={e => setKeyword(e.target.value)} />
                  </div>
                </div>
                <div className="filter-actions">
                  <button className="btn btn--secondary btn--sm">查询</button>
                  <button className="btn btn--text btn--sm">重置</button>
                  <button className="btn btn--primary btn--sm"><Icon.External size={14} /> 导出</button>
                </div>
              </div>

              <div className="table-wrap" data-region="admin-user-table">
                <table className="data-table">
                  <thead>
                    <tr>
                      <th>ID</th><th>邮箱</th><th>手机号</th><th>企业名</th><th>状态</th>
                      <th>注册时间</th><th>最近登录</th><th>来源</th><th>操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filtered.map(u => (
                      <tr key={u.id}>
                        <td>{u.id}</td>
                        <td>{u.email}</td>
                        <td>{u.phone}</td>
                        <td>{u.company}</td>
                        <td><StateTag state={u.state} /></td>
                        <td>{u.regTime}</td>
                        <td>{u.lastLogin}</td>
                        <td><span className="tag tag--neutral">{u.source}</span></td>
                        <td>
                          <button className="btn btn--text btn--sm" onClick={() => setDetailUser(u)}>详情/审核</button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              <div className="pagination" data-region="admin-user-pagination">
                <span className="pagination-info">共 {filtered.length} 条</span>
                <div className="pagination-btns">
                  <button className="btn btn--text btn--sm">&lt;</button>
                  <button className="btn btn--text btn--sm pagination-btn--active">1</button>
                  <button className="btn btn--text btn--sm">2</button>
                  <button className="btn btn--text btn--sm">&gt;</button>
                </div>
              </div>
            </div>
          </main>
          <Footer />
        </div>
      </div>

      {detailUser && (
        <UserDetailModal
          user={detailUser}
          onClose={() => setDetailUser(null)}
          onApprove={handleApprove}
          onReject={handleReject}
          onSendReminder={handleSendReminder}
        />
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<UserQuery />);
