// 规则库 — 行业规则包 / AIGC 护栏包的上传与查看（原 AIDS 拆解库的 rules tab 拆出）

const RulePackPage = () => {
  const [packs, setPacks] = React.useState([]);
  const [selPackId, setSelPackId] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState("");
  const [uploading, setUploading] = React.useState(false);
  const uploadRef = React.useRef(null);

  React.useEffect(() => { loadRules(); }, []);

  const loadRules = async () => {
    setLoading(true); setErr("");
    try {
      const d = await API.rulePacks.list();
      const items = d.items || [];
      setPacks(items);
      if (items.length && !selPackId) setSelPackId(items[0].pack_id);
    } catch (e) { setErr(String(e.message || e)); }
    finally { setLoading(false); }
  };

  const selPack = packs.find(p => p.pack_id === selPackId);

  const onUploadRule = async (file) => {
    if (!file) return;
    const form = new FormData();
    form.append("file", file);
    form.append("display_name", file.name.replace(/\.[^.]+$/, ""));
    setUploading(true);
    try {
      await API.rulePacks.upload(form);
      await loadRules();
    } catch (e) { setErr(String(e.message || e)); }
    finally { setUploading(false); }
  };

  return (
    <>
      <Topbar
        crumbs={["资产", "规则库"]}
        right={
          <>
            <button className="btn primary" onClick={() => uploadRef.current && uploadRef.current.click()} disabled={uploading}>
              <Icon name="download" size={11}/>{uploading ? "上传中" : "上传规则包"}
            </button>
            <input ref={uploadRef} type="file" accept=".md,.pdf" style={{display:"none"}} onChange={e => onUploadRule(e.target.files[0])} />
          </>
        }
      />

      {err && (
        <div style={{margin:"10px 16px 0", padding:"10px 12px", background:"var(--pink-soft)", border:"1px solid var(--pink)", borderRadius:5, fontSize:11, color:"var(--pink)"}}>
          {err}
        </div>
      )}

      <div className="main-body">
        {/* 左：规则包列表 */}
        <div className="col scroll" style={{width:280, flexShrink:0, padding:"12px 10px", gap:6, borderRight:"1px solid var(--line-soft)", background:"var(--bg-0)"}}>
          <div className="row between" style={{padding:"0 4px 6px"}}>
            <span className="kpi-l">规则包</span>
            <span className="mono" style={{fontSize:10, color:"var(--fg-3)"}}>{packs.length} 条</span>
          </div>
          {loading && !packs.length && <div style={{fontSize:11, color:"var(--fg-3)", padding:20, textAlign:"center"}}>加载中…</div>}
          {packs.map(p => (
            <div key={p.pack_id} onClick={() => setSelPackId(p.pack_id)} className="row gap-8" style={{
              padding:8, borderRadius:5, cursor:"pointer", alignItems:"flex-start",
              background: p.pack_id===selPackId ? "color-mix(in oklch, var(--cyan) 10%, var(--bg-1))" : "var(--bg-1)",
              border: `1px solid ${p.pack_id===selPackId ? "var(--cyan)" : "var(--line-1)"}`,
            }}>
              <div className="col grow gap-2" style={{minWidth:0}}>
                <span style={{fontSize:11.5, fontWeight:600, color:"var(--fg-0)"}}>{p.display_name}</span>
                <div className="row gap-4" style={{flexWrap:"wrap"}}>
                  <span className="tag" style={{fontSize:9}}>{p.category==="industry_rule_pack" ? "行业规则" : "AIGC护栏"}</span>
                  {p.industry_key && <span className="tag cyan" style={{fontSize:9}}>{p.industry_key}</span>}
                </div>
                <span className="mono" style={{fontSize:9.5, color:"var(--fg-3)"}}>{p.size_kb} KB · {p.created_at ? p.created_at.slice(0,16).replace("T"," ") : ""}</span>
              </div>
            </div>
          ))}
          {!loading && !packs.length && <div style={{fontSize:11, color:"var(--fg-3)", padding:20, textAlign:"center"}}>暂无规则包</div>}
        </div>

        {/* 右：规则包详情 */}
        <div className="col scroll grow" style={{padding:"12px 14px 20px", gap:12, background:"var(--bg-0)", minWidth:0}}>
          {selPack && (
            <div className="card" style={{overflow:"hidden"}}>
              <div className="card-hd">
                <span className="card-title">{selPack.display_name}</span>
                <span className={`tag ${selPack.category==="industry_rule_pack"?"cyan":"purple"}`} style={{fontSize:9}}>
                  {selPack.category==="industry_rule_pack" ? "行业规则" : "AIGC护栏"}
                </span>
              </div>
              <div className="col" style={{padding:12, gap:10}}>
                <div className="row gap-16" style={{flexWrap:"wrap"}}>
                  <div className="col gap-2"><span className="kpi-l">ID</span><span className="mono" style={{fontSize:11, color:"var(--fg-1)"}}>{selPack.pack_id}</span></div>
                  <div className="col gap-2"><span className="kpi-l">大小</span><span className="mono" style={{fontSize:11, color:"var(--fg-1)"}}>{selPack.size_kb} KB</span></div>
                  <div className="col gap-2"><span className="kpi-l">文件名</span><span className="mono" style={{fontSize:11, color:"var(--fg-1)"}}>{selPack.filename}</span></div>
                  <div className="col gap-2"><span className="kpi-l">创建时间</span><span className="mono" style={{fontSize:11, color:"var(--fg-1)"}}>{selPack.created_at ? selPack.created_at.slice(0,16).replace("T"," ") : "—"}</span></div>
                  {selPack.industry_key && (
                    <div className="col gap-2"><span className="kpi-l">行业</span><span className="tag cyan" style={{fontSize:9}}>{selPack.industry_key}</span></div>
                  )}
                </div>
                <div style={{padding:10, background:"var(--bg-1)", borderRadius:5, border:"1px dashed var(--line-2)", fontSize:11, color:"var(--fg-3)", lineHeight:1.6}}>
                  <b>文件路径：</b><span className="mono">{selPack.file_path}</span>
                  <br/><b>内容类型：</b>{selPack.content_type}
                  <br/><b>状态：</b>{selPack.enabled ? "已启用" : "已禁用"}
                  <br/><b>备注：</b>{selPack.note || "—"}
                </div>
                {selPack.filename.endsWith(".md") && (
                  <div className="col gap-4">
                    <span className="kpi-l">内容预览</span>
                    <div style={{padding:10, background:"var(--bg-1)", borderRadius:5, border:"1px solid var(--line-1)", fontSize:11.5, color:"var(--fg-2)", lineHeight:1.7, maxHeight:300, overflow:"auto", whiteSpace:"pre-wrap"}}>
                      （文本型规则包内容需在服务端读取，此处仅展示元信息）
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}

          {!selPack && (
            <div className="card col center" style={{padding:"40px 20px", gap:10, textAlign:"center"}}>
              <Icon name="filter" size={24} style={{color:"var(--fg-3)"}} />
              <div style={{fontSize:13, color:"var(--fg-1)", fontWeight:500}}>请在左侧选择一个规则包</div>
              <div style={{fontSize:11, color:"var(--fg-3)", lineHeight:1.5}}>或点击右上角「上传规则包」上传 .md / .pdf 文件</div>
            </div>
          )}
        </div>
      </div>
    </>
  );
};

Object.assign(window, { RulePackPage });
