/* ============================================================
   page-settle.jsx — 结算中心（行级存储版）
   每条记录独立一行，并发安全，操作直接读写 settle_out / settle_in 表
   ============================================================ */

const S_TH = { padding: "8px 10px", textAlign: "left", fontWeight: 600, fontSize: 11.5, color: "var(--ink-2)", whiteSpace: "nowrap", background: "var(--bg-2)" };
const S_TD = { padding: "0 10px", height: 44, overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis", maxWidth: 0, verticalAlign: "middle", fontSize: 12.5 };
const PAYER_OPTS    = ["深圳不鸣", "沈阳不鸣", "幕后玩家", "深圳业鱼", "业鱼", "惊人"];
const RECEIVER_OPTS = ["深圳不鸣", "沈阳不鸣", "幕后玩家", "深圳业鱼", "业鱼", "惊人"];
const OVERALL_COLOR = { "已完成":"var(--ink-4)", "待打款":"#2563eb", "待开票":"#d97706", "待盖章":"#d97706", "待确认":"var(--vermilion)" };

/* ── 单行状态下拉 ── */
function StatusCell({ val, opts, onSave }) {
  const { editing } = useEditMode();
  const done = val && val.startsWith("已");
  return (
    <td style={{ ...S_TD, maxWidth:"none", textAlign:"center" }}>
      {editing ? (
        <select value={val || opts[0]} onChange={e => onSave(e.target.value)}
          style={{ fontSize:11.5, padding:"2px 6px", border:"1px solid var(--border)", borderRadius:4,
            background:"transparent", color:done?"var(--ink-3)":"var(--vermilion)", cursor:"pointer" }}>
          {opts.map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      ) : <span style={{ fontSize:11.5, color:done?"var(--ink-3)":"var(--vermilion)", fontWeight:done?400:500 }}>{val||opts[0]}</span>}
    </td>
  );
}

/* ── 下拉选择格 ── */
function SelectCell({ val, opts, onSave, placeholder }) {
  const { editing } = useEditMode();
  return (
    <td style={{ ...S_TD, maxWidth:"none" }}>
      {editing ? (
        <select value={val||""} onChange={e => onSave(e.target.value)}
          style={{ fontSize:12.5, padding:"2px 6px", border:"1px solid var(--border)", borderRadius:4,
            background:"transparent", color:val?"var(--ink-1)":"var(--ink-4)", cursor:"pointer", width:"100%" }}>
          <option value="">{placeholder||"—"}</option>
          {opts.map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      ) : <span style={{ color:val?"var(--ink-1)":"var(--ink-4)" }}>{val||"—"}</span>}
    </td>
  );
}

/* ── 文件附件格（Supabase Storage + 外链）── */
function FileCell({ val, onSave, rowId, fkey }) {
  const { editing } = useEditMode();
  const [uploading, setUploading] = useState(false);
  const [pct, setPct] = useState(0);
  const inputId = `sf-${rowId}-${fkey}`;
  const parsed = !val ? null : (typeof val==="object" ? val : { name: val });
  const href = parsed?.url || parsed?.external_url;

  const onPick = async (e) => {
    const f = e.target.files?.[0]; if (!f) return;
    if (f.size > 209715200) { alert("文件超过 200 MB"); e.target.value=""; return; }
    setUploading(true); setPct(20);
    try {
      const stem = f.name.replace(/[^A-Za-z0-9_\-\.]/g,"_").slice(0,60)||"file";
      const path = `settle/${rowId}_${Date.now()}_${stem}`;
      setPct(40);
      const { error } = await _sb.storage.from("manju-files").upload(path, f, { upsert:false });
      if (error) throw new Error(error.message);
      setPct(80);
      const { data:pub } = _sb.storage.from("manju-files").getPublicUrl(path);
      onSave({ name:f.name, storage_path:path, url:pub.publicUrl, size:f.size });
      setPct(100);
    } catch(err) { alert("上传失败: "+(err.message||"请重试")); }
    finally { setUploading(false); setPct(0); e.target.value=""; }
  };

  const pasteLink = () => {
    const url = prompt("粘贴飞书/网盘链接"); if (!url) return;
    const name = prompt("文件名称（可空）")||url.split("/").pop().split("?")[0]||"对账文件";
    onSave({ name, external_url:url });
  };

  if (!editing) {
    if (!parsed) return <td style={S_TD}>—</td>;
    return <td style={{ ...S_TD, maxWidth:"none" }}>
      {href ? <a href={href} target="_blank" rel="noopener"
        style={{ color:"var(--vermilion)", textDecoration:"none", fontSize:12 }} title={parsed.name}>
        ↗ {parsed.name||"查看"}
      </a> : <span style={{ color:"var(--ink-3)", fontSize:12 }} title={parsed.name}>{parsed.name||"—"}</span>}
    </td>;
  }

  return (
    <td style={{ ...S_TD, maxWidth:"none", padding:"4px 8px" }}>
      {uploading ? (
        <div style={{ fontSize:11, color:"var(--ink-3)", minWidth:100 }}>
          上传中 {pct}%
          <div style={{ height:3, background:"var(--border)", borderRadius:2, marginTop:3 }}>
            <div style={{ width:pct+"%", height:"100%", background:"var(--vermilion)", transition:"width .2s" }}/>
          </div>
        </div>
      ) : href ? (
        <div style={{ display:"flex", alignItems:"center", gap:6 }}>
          <a href={href} target="_blank" rel="noopener"
            style={{ color:"var(--vermilion)", textDecoration:"none", fontSize:11.5, flex:1, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}
            title={parsed.name}>↗ {parsed.name}</a>
          <button onClick={() => onSave(null)}
            style={{ flexShrink:0, fontSize:10, padding:"1px 5px", border:"1px solid var(--border)", borderRadius:3, cursor:"pointer", background:"transparent", color:"var(--ink-4)" }}>替换</button>
        </div>
      ) : (
        <div style={{ display:"flex", gap:4, alignItems:"center" }}>
          <label htmlFor={inputId} style={{ fontSize:11, padding:"2px 8px", border:"1px dashed var(--border)", borderRadius:3, cursor:"pointer", color:"var(--ink-3)", whiteSpace:"nowrap" }}>↑ 上传</label>
          <input id={inputId} type="file" accept=".xlsx,.xls,.pdf,.ofd,.zip" onChange={onPick} style={{ display:"none" }}/>
          <button onClick={pasteLink}
            style={{ fontSize:11, padding:"2px 8px", border:"1px dashed var(--border)", borderRadius:3, cursor:"pointer", color:"var(--ink-3)", background:"transparent", whiteSpace:"nowrap" }}>🔗 链接</button>
          {parsed?.name && <span style={{ fontSize:10, color:"var(--ink-4)", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{parsed.name}</span>}
        </div>
      )}
    </td>
  );
}

/* ── 可编辑文本格（直接保存行）── */
function TextCell({ val, onSave, placeholder, mono }) {
  const { editing } = useEditMode();
  const [draft, setDraft] = useState(val||"");
  useEffect(() => { setDraft(val||""); }, [val]);
  if (!editing) return <td style={{ ...S_TD, maxWidth:0, fontFamily:mono?"var(--font-mono)":undefined }}>{val||"—"}</td>;
  return (
    <td style={{ ...S_TD, maxWidth:0 }}>
      <input value={draft} onChange={e => setDraft(e.target.value)}
        onBlur={() => { if (draft !== (val||"")) onSave(draft); }}
        onKeyDown={e => { if (e.key==="Enter") { e.target.blur(); } }}
        placeholder={placeholder||"—"}
        style={{ width:"100%", background:"transparent", border:"none", outline:"none",
          fontSize:12.5, fontFamily:mono?"var(--font-mono)":undefined, color:"var(--ink-1)" }}/>
    </td>
  );
}

/* ══════════════════════════════════════════════════════════════
   主页面
══════════════════════════════════════════════════════════════ */
function PageSettle() {
  const { editing } = useEditMode();
  const [tab, setTab]   = useState("out");
  const [rows, setRows] = useState([]);
  const [loading, setLoading] = useState(true);
  const [monthFilter, setMF]  = useState("__all__");
  const [holderFilter, setHF] = useState("__all__");
  const [statusFilter, setSF] = useState("__all__");
  const table = tab === "out" ? "settle_out" : "settle_in";

  const publisherOpts = useMemo(() => {
    const seedNames = (window.__SEED__?.PUBLISHERS||[]).map(p=>p.name).filter(Boolean);
    // 合并种子名称 + 数据库中实际存在的值（防止名称不一致导致下拉显示占位符）
    const extra = ["看点"]; // 飞书原始数据用"看点"，种子用"看点短篇"
    return [...new Set([...extra, ...seedNames])].sort();
  }, []);

  /* 拉全表 */
  const load = useCallback(async () => {
    setLoading(true);
    const { data, error } = await _sb.from(table).select("*").order("month", { ascending:false });
    if (!error && data) setRows(data);
    setLoading(false);
  }, [table]);

  useEffect(() => { load(); }, [load]);

  /* 保存单个字段 */
  const saveField = async (id, field, value) => {
    // 乐观更新
    setRows(prev => prev.map(r => r.id===id ? { ...r, [field]:value, updated_at:new Date().toISOString() } : r));
    const { error } = await _sb.from(table).update({ [field]:value, updated_at:new Date().toISOString() }).eq("id", id);
    if (error) { alert("保存失败: "+error.message); load(); }
  };

  /* 新增行 */
  const addRow = async () => {
    const blank = tab==="out"
      ? { id:`so-${Date.now()}`, month:"", holder:"", amount:null, s_confirm:"待确认", s_seal:"待盖章", s_invoice:"待开票", s_payment:"待打款", payer:"", invoice_file:null, reconcile_file:null, note:"" }
      : { id:`si-${Date.now()}`, month:"", holder:"", amount:null, s_confirm:"待确认", s_invoice:"待开票", s_payment:"待打款", receiver:"", reconcile_file:null, note:"" };
    const { error } = await _sb.from(table).insert(blank);
    if (error) { alert("新增失败: "+error.message); return; }
    setRows(prev => [blank, ...prev]);
  };

  /* 删除行 */
  const delRow = async (id) => {
    if (!confirm("确认删除？")) return;
    const { error } = await _sb.from(table).delete().eq("id", id);
    if (error) { alert("删除失败: "+error.message); return; }
    setRows(prev => prev.filter(r => r.id!==id));
  };

  const getStatus = (r) => {
    if (tab==="out") {
      if (r.s_payment==="已打款") return "已完成";
      if (r.s_invoice==="已开票") return "待打款";
      if (r.s_seal   ==="已盖章") return "待开票";
      if (r.s_confirm==="已确认") return "待盖章";
      return "待确认";
    } else {
      if (r.s_payment==="已打款") return "已完成";
      if (r.s_invoice==="已开票") return "待打款";
      if (r.s_confirm==="已确认") return "待开票";
      return "待确认";
    }
  };

  const months  = [...new Set(rows.map(r=>r.month).filter(Boolean))].sort().reverse();
  const holders = [...new Set(rows.map(r=>r.holder).filter(Boolean))].sort();

  const visible = rows.filter(r =>
    (monthFilter ==="__all__"||r.month ===monthFilter) &&
    (holderFilter==="__all__"||r.holder===holderFilter) &&
    (statusFilter==="__all__"||getStatus(r)===statusFilter)
  );
  const totalAmt = visible.reduce((s,r) => s+(parseFloat(r.amount)||0), 0);

  const tabBtn = (id, label, sub) => (
    <button onClick={() => { setTab(id); setMF("__all__"); setHF("__all__"); setSF("__all__"); }}
      style={{ padding:"10px 28px", border:"none", cursor:"pointer", background:"transparent",
        borderBottom:tab===id?"2px solid var(--vermilion)":"2px solid transparent",
        fontWeight:tab===id?600:400, color:tab===id?"var(--ink-1)":"var(--ink-3)", fontSize:13 }}>
      {label}<span style={{ fontSize:11, display:"block", color:"var(--ink-4)", fontWeight:400 }}>{sub}</span>
    </button>
  );

  const sel = (val, setter, opts, ph) => (
    <select value={val} onChange={e=>setter(e.target.value)}
      style={{ padding:"4px 10px", fontSize:12, border:"1px solid var(--border)", borderRadius:4, background:"var(--bg-1)" }}>
      <option value="__all__">{ph}</option>
      {opts.map(o=><option key={o} value={o}>{o}</option>)}
    </select>
  );

  return (
    <>
      <FolderHead index="06" title="结算中心" sub="结算单收集 · 收入 / 支出状态跟踪（行级存储）" />

      <div style={{ display:"flex", borderBottom:"2px solid var(--border)", marginBottom:20 }}>
        {tabBtn("out","支出结算","我们付 → 版权方")}
        {tabBtn("in", "收入结算","版权方付 → 我们")}
      </div>

      <div style={{ display:"flex", gap:10, marginBottom:16, alignItems:"center", flexWrap:"wrap" }}>
        {sel(monthFilter,  setMF, months,      "全部月份")}
        {sel(holderFilter, setHF, holders,     "全部版权方")}
        {sel(statusFilter, setSF, ["待确认","待盖章","待开票","待打款","已完成"], "全部状态")}
        {loading && <span style={{ fontSize:12, color:"var(--ink-4)" }}>加载中…</span>}
        {!loading && <span style={{ fontSize:12, color:"var(--ink-4)" }}>{visible.length} 条</span>}
        {visible.length>0 && (
          <span style={{ marginLeft:"auto", fontSize:12.5, fontWeight:600, fontFamily:"var(--font-mono)" }}>
            合计 ¥{totalAmt.toLocaleString("zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2})}
          </span>
        )}
      </div>

      <div style={{ overflowX:"auto" }}>
        <table style={{ width:"100%", borderCollapse:"collapse", fontSize:12.5, tableLayout:"fixed" }}>
          <colgroup>
            <col style={{width:80}}/><col style={{width:90}}/><col style={{width:90}}/>
            {tab==="out" ? <>
              <col style={{width:78}}/><col style={{width:78}}/><col style={{width:78}}/><col style={{width:78}}/>
              <col style={{width:88}}/><col style={{width:160}}/><col style={{width:160}}/>
            </> : <>
              <col style={{width:78}}/><col style={{width:78}}/><col style={{width:78}}/>
              <col style={{width:88}}/><col style={{width:160}}/>
            </>}
            <col style={{width:68}}/><col/>{editing&&<col style={{width:36}}/>}
          </colgroup>
          <thead>
            <tr style={{ borderBottom:"2px solid var(--border)" }}>
              <th style={S_TH}>月份</th>
              <th style={S_TH}>版权方</th>
              <th style={{...S_TH,textAlign:"right"}}>金额</th>
              {tab==="out" ? <>
                <th style={{...S_TH,textAlign:"center"}}>版权方确认</th>
                <th style={{...S_TH,textAlign:"center"}}>结算单盖章</th>
                <th style={{...S_TH,textAlign:"center"}}>版权方开票</th>
                <th style={{...S_TH,textAlign:"center"}}>我们打款</th>
                <th style={S_TH}>打款主体</th>
                <th style={S_TH}>对账表</th>
                <th style={S_TH}>发票文件</th>
              </> : <>
                <th style={{...S_TH,textAlign:"center"}}>我们确认</th>
                <th style={{...S_TH,textAlign:"center"}}>我们开票</th>
                <th style={{...S_TH,textAlign:"center"}}>版权方打款</th>
                <th style={S_TH}>收款主体</th>
                <th style={S_TH}>对账表</th>
              </>}
              <th style={{...S_TH,textAlign:"center"}}>进度</th>
              <th style={S_TH}>备注</th>
              {editing&&<th style={S_TH}></th>}
            </tr>
          </thead>
          <tbody>
            {!loading && visible.length===0 && (
              <tr><td colSpan={20} style={{padding:"32px",color:"var(--ink-4)",textAlign:"center",fontStyle:"italic"}}>
                暂无结算记录{editing?" · 点击下方「新增记录」":""}
              </td></tr>
            )}
            {visible.map(r => {
              const sv = (field, val) => saveField(r.id, field, val);
              const overall = getStatus(r);
              return (
                <tr key={r.id} style={{borderBottom:"1px solid var(--border)"}}>
                  <TextCell val={r.month}  onSave={v=>sv("month",v)}  placeholder="2025-08" />
                  <SelectCell val={r.holder} opts={publisherOpts} onSave={v=>sv("holder",v)} placeholder="版权方" />
                  <TextCell val={r.amount!=null?String(r.amount):""} onSave={v=>sv("amount",v?parseFloat(v):null)} placeholder="0.00" mono />
                  {tab==="out" ? <>
                    <StatusCell val={r.s_confirm} opts={["待确认","已确认"]} onSave={v=>sv("s_confirm",v)} />
                    <StatusCell val={r.s_seal}    opts={["待盖章","已盖章"]} onSave={v=>sv("s_seal",v)} />
                    <StatusCell val={r.s_invoice} opts={["待开票","已开票"]} onSave={v=>sv("s_invoice",v)} />
                    <StatusCell val={r.s_payment} opts={["待打款","已打款"]} onSave={v=>sv("s_payment",v)} />
                    <SelectCell val={r.payer}    opts={PAYER_OPTS}    onSave={v=>sv("payer",v)}    placeholder="打款主体" />
                    <FileCell val={r.reconcile_file} onSave={v=>sv("reconcile_file",v)} rowId={r.id} fkey="rec" />
                    <FileCell val={r.invoice_file}   onSave={v=>sv("invoice_file",v)}   rowId={r.id} fkey="inv" />
                  </> : <>
                    <StatusCell val={r.s_confirm} opts={["待确认","已确认"]} onSave={v=>sv("s_confirm",v)} />
                    <StatusCell val={r.s_invoice} opts={["待开票","已开票"]} onSave={v=>sv("s_invoice",v)} />
                    <StatusCell val={r.s_payment} opts={["待打款","已打款"]} onSave={v=>sv("s_payment",v)} />
                    <SelectCell val={r.receiver} opts={RECEIVER_OPTS} onSave={v=>sv("receiver",v)} placeholder="收款主体" />
                    <FileCell val={r.reconcile_file} onSave={v=>sv("reconcile_file",v)} rowId={r.id} fkey="rec" />
                  </>}
                  <td style={{...S_TD,textAlign:"center",maxWidth:"none"}}>
                    <span style={{fontSize:11,padding:"2px 8px",borderRadius:10,background:"var(--bg-2)",
                      color:OVERALL_COLOR[overall]||"var(--ink-2)"}}>{overall}</span>
                  </td>
                  <TextCell val={r.note} onSave={v=>sv("note",v)} placeholder="—" />
                  {editing && (
                    <td style={{...S_TD,textAlign:"center",maxWidth:"none"}}>
                      <button className="btn-del" onClick={()=>delRow(r.id)}>×</button>
                    </td>
                  )}
                </tr>
              );
            })}
          </tbody>
        </table>
        {editing && (
          <div style={{marginTop:10}}>
            <button className="btn-add" onClick={addRow}>＋ 新增记录</button>
          </div>
        )}
      </div>
    </>
  );
}

Object.assign(window, { PageSettle });
