window.FB = window.FB || {};
FB.SopTab = function SopTab({ lang }) {
  const { useState, useEffect } = React;
  const t = FB.makeT(lang);
  const [goods, setGoods] = useState(null);
  const [sel, setSel] = useState("");
  const [rec, setRec] = useState(null);
  const [batch, setBatch] = useState(1);
  const [photo, setPhoto] = useState(null);

  useEffect(() => { FB.api.finishedForProd().then((g) => { setGoods(g); if (g.length) { setSel(g[0].code); } }); }, []);
  useEffect(() => { if (sel) { setRec(null); FB.api.sopRecipe(sel).then(setRec); } }, [sel]);

  const nm = (g) => lang === "zh" ? g.name_cn : lang === "vi" ? (g.name_vn || g.name_en) : (g.name_en || g.name_cn);
  const iname = (code) => {
    const i = rec && rec.names[code];
    return i ? (lang === "zh" ? i.name_cn : lang === "vi" ? (i.name_vn || i.name_en) : (i.name_en || i.name_cn)) : code;
  };
  const yieldQty = rec && rec.spec ? Number(rec.spec.batch_yield) * batch : null;

  return (
    <div className="px-3 py-3 max-w-md mx-auto pb-20">
      {!goods && <p className="text-sm text-stone-400">{t("loading")}</p>}
      {goods && (
        <select value={sel} onChange={(e) => setSel(e.target.value)} className="w-full mb-3 px-3 h-12 rounded-xl border border-stone-300 bg-white text-[15px]">
          {goods.map((g) => <option key={g.code} value={g.code}>{nm(g)} · {g.code}</option>)}
        </select>
      )}

      {sel && (
        <button onClick={() => { const g = (goods || []).find((x) => x.code === sel); if (g) setPhoto({ code: g.code, name: nm(g) }); }}
          className="w-full mb-3 h-10 rounded-xl border border-stone-200 bg-white text-[12px] text-stone-500 active:bg-stone-50 flex items-center justify-center gap-1.5">
          <FB.UI.Icon name="image" size={14} />{lang === "zh" ? "看成品照片" : lang === "vi" ? "Xem hình thành phẩm" : "View product photo"}
        </button>
      )}

      <div className="flex items-center justify-between rounded-xl border border-stone-200 bg-white px-3 py-2.5 mb-3" style={{ borderLeft: "3px solid #B91C1C" }}>
        <span className="text-[13px] font-semibold text-red-700">{t("batch")}</span>
        <div className="flex items-center gap-3">
          <button onClick={() => setBatch((b) => Math.max(1, b - 1))} className="w-10 h-10 rounded-xl border border-stone-200 text-stone-500 flex items-center justify-center active:bg-stone-100"><FB.UI.Icon name="minus" size={16} /></button>
          <span className="text-[19px] font-bold text-red-700 w-8 text-center tabular-nums">{batch}</span>
          <button onClick={() => setBatch((b) => b + 1)} className="w-10 h-10 rounded-xl border border-stone-200 text-stone-500 flex items-center justify-center active:bg-stone-100"><FB.UI.Icon name="plus" size={16} /></button>
        </div>
      </div>

      {!rec && <p className="text-sm text-stone-400">{t("loading")}</p>}
      {rec && (
        <>
          <p className="text-xs text-stone-400 font-medium px-1 mb-1">{t("ingredients")}</p>
          <div className="rounded-xl border border-stone-200 bg-white divide-y divide-stone-100 overflow-hidden mb-3">
            {rec.bom.length === 0 && <div className="px-3 py-3 text-sm text-stone-400">{t("noData")}</div>}
            {rec.bom.map((b, i) => {
              const perPack = (FB.PER_PACK_ITEMS || []).indexOf(b.input_code) >= 0;
              const packs = rec.spec ? Number(rec.spec.batch_yield) * batch : batch;
              const need = Number(b.qty) * (perPack ? packs : batch);
              return (
                <div key={i} className="flex items-center justify-between px-4 py-2.5">
                  <span className="text-[14px] text-stone-700" onClick={() => setPhoto({ code: b.input_code, name: iname(b.input_code) })}>
                    {iname(b.input_code)}
                    {perPack ? <span className="ml-1.5 text-[10px] text-stone-400">/pack</span> : null}
                  </span>
                  <span className="text-[15px] font-semibold text-stone-900 tabular-nums">
                    {Math.round(need * 100) / 100}<span className="text-[10px] text-stone-400 font-normal ml-1">{b.unit}</span>
                  </span>
                </div>
              );
            })}
          </div>
          {yieldQty != null && (
            <div className="rounded-xl px-3 py-2.5 text-sm flex items-center gap-2" style={{ background: "#F0F6E8", color: "#4A7A1C" }}>
              <FB.UI.Icon name="production" size={15} />
              {t("yield")}: <span className="font-bold tabular-nums">{Math.round(yieldQty * 100) / 100}</span> {rec.spec.yield_unit || ""}
            </div>
          )}
          {photo && <FB.PhotoView code={photo.code} name={photo.name} lang={lang} onClose={() => setPhoto(null)} />}
          <p className="text-[11px] text-stone-400 mt-2 px-1">{t("packNote")}</p>
          <p className="text-[11px] text-stone-400 mt-3 px-1">{t("steps")}: {lang === "zh" ? "待补(admin 以后可加)" : lang === "vi" ? "sẽ bổ sung sau" : "to be added"}</p>
        </>
      )}
    </div>
  );
};
