const { useState: useStateSR, useEffect: useEffectSR, useRef: useRefSR } = React;

// ── Modal shell ────────────────────────────────────────────────────────────────

const SRModal = ({ title, onClose, children }) => (
  <div
    style={{
      position: "fixed", inset: 0, zIndex: 100,
      background: "rgba(0,0,0,0.35)", display: "flex",
      alignItems: "center", justifyContent: "center",
    }}
    onClick={e => { if (e.target === e.currentTarget) onClose(); }}
  >
    <div className="panel" style={{ width: 460, maxHeight: "90vh", overflow: "auto", padding: 24 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18 }}>
        <span style={{ fontWeight: 600, fontSize: 14 }}>{title}</span>
        <button className="btn ghost" onClick={onClose} style={{ height: 24, padding: "0 8px" }}>✕</button>
      </div>
      {children}
    </div>
  </div>
);

const SRField = ({ label, hint, children }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
    <label style={{ fontSize: 11, fontWeight: 500, color: "var(--ink-2)", textTransform: "uppercase", letterSpacing: "0.06em", fontFamily: "var(--font-mono)" }}>
      {label}
    </label>
    {children}
    {hint && <span style={{ fontSize: 11, color: "var(--ink-3)" }}>{hint}</span>}
  </div>
);

const srInputStyle = {
  padding: "7px 10px", fontSize: 13, borderRadius: 5,
  border: "1px solid var(--hairline)", background: "var(--surface-2)",
  color: "var(--ink)", outline: "none", fontFamily: "var(--font-sans)", width: "100%",
};

async function srUploadImage(sb, file, path) {
  const { data, error } = await sb.storage.from("media").upload(path, file, { upsert: true, contentType: file.type });
  if (error) throw new Error(error.message || error.error || JSON.stringify(error));
  const { data: urlData } = sb.storage.from("media").getPublicUrl(data.path);
  return urlData.publicUrl;
}

const SRLogoField = ({ value, onChange }) => {
  const inputRef = useRefSR(null);
  const [preview, setPreview] = useStateSR(value || "");
  const [status, setStatus] = useStateSR(null);

  useEffectSR(() => { setPreview(value || ""); }, [value]);

  const handleFile = async (e) => {
    const file = e.target.files?.[0];
    e.target.value = "";
    if (!file) return;
    const sb = window.supabaseClient;
    try {
      setStatus("Uploading…");
      const path = `wishlist-stores/${Date.now()}_${file.name}`;
      const url = await srUploadImage(sb, file, path);
      setPreview(url);
      onChange(url);
      setStatus(null);
    } catch (err) {
      setStatus(null);
      alert("Upload failed: " + err.message);
    }
  };

  return (
    <SRField label="Logo">
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{
          width: 52, height: 52, borderRadius: 8, background: "var(--surface-3)",
          border: "1px solid var(--hairline)", overflow: "hidden",
          display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
        }}>
          {preview
            ? <img src={preview} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
            : <span style={{ fontSize: 20 }}>🏬</span>}
        </div>
        <div style={{ flex: 1 }}>
          <input
            type="url"
            value={preview}
            onChange={e => { setPreview(e.target.value); onChange(e.target.value); }}
            placeholder="Paste logo URL or upload →"
            style={{ ...srInputStyle, fontSize: 12, fontFamily: "var(--font-mono)" }}
          />
          <input ref={inputRef} type="file" accept="image/*" style={{ display: "none" }} onChange={handleFile} />
          <button className="btn ghost" style={{ marginTop: 4, height: 24, fontSize: 11 }} onClick={() => inputRef.current?.click()} disabled={!!status}>
            {status ?? "Upload image"}
          </button>
        </div>
      </div>
    </SRField>
  );
};

// ── StoreRequestModal (create/edit a curated wishlist store) ───────────────────

const StoreRequestModal = ({ initial, onSave, onClose }) => {
  const [name, setName] = useStateSR(initial?.name || "");
  const [logoUrl, setLogoUrl] = useStateSR(initial?.logo_url || "");
  const [category, setCategory] = useStateSR(initial?.category || "");
  const [description, setDescription] = useStateSR(initial?.description || "");
  const [instagramUrl, setInstagramUrl] = useStateSR(initial?.instagram_url || "");
  const [facebookUrl, setFacebookUrl] = useStateSR(initial?.facebook_url || "");
  const [tiktokUrl, setTiktokUrl] = useStateSR(initial?.tiktok_url || "");
  const [websiteUrl, setWebsiteUrl] = useStateSR(initial?.website_url || "");
  const [status, setStatus] = useStateSR(initial?.status || "active");
  const [saving, setSaving] = useStateSR(false);
  const [err, setErr] = useStateSR(null);

  const handleSubmit = async () => {
    if (!name.trim()) { setErr("Name is required."); return; }
    setSaving(true);
    setErr(null);
    try {
      await onSave({
        name: name.trim(),
        logo_url: logoUrl || null,
        category: category.trim() || null,
        description: description.trim() || null,
        instagram_url: instagramUrl.trim() || null,
        facebook_url: facebookUrl.trim() || null,
        tiktok_url: tiktokUrl.trim() || null,
        website_url: websiteUrl.trim() || null,
        status,
      });
      onClose();
    } catch (e) {
      setErr(e.message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <SRModal title={initial ? "Edit store" : "New store"} onClose={onClose}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <SRField label="Store name">
          <input style={srInputStyle} value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Daraz Fashion" />
        </SRField>
        <SRLogoField value={logoUrl} onChange={setLogoUrl} />
        <SRField label="Category">
          <input style={srInputStyle} value={category} onChange={e => setCategory(e.target.value)} placeholder="e.g. Fashion, Electronics, Groceries" />
        </SRField>
        <SRField label="Description" hint="Shown to buyers on the wishlist card.">
          <textarea style={{ ...srInputStyle, minHeight: 60, resize: "vertical" }} value={description} onChange={e => setDescription(e.target.value)} placeholder="Short blurb about the store" />
        </SRField>
        <SRField label="Instagram">
          <input style={srInputStyle} value={instagramUrl} onChange={e => setInstagramUrl(e.target.value)} placeholder="https://instagram.com/..." />
        </SRField>
        <SRField label="Facebook">
          <input style={srInputStyle} value={facebookUrl} onChange={e => setFacebookUrl(e.target.value)} placeholder="https://facebook.com/..." />
        </SRField>
        <SRField label="TikTok">
          <input style={srInputStyle} value={tiktokUrl} onChange={e => setTiktokUrl(e.target.value)} placeholder="https://tiktok.com/@..." />
        </SRField>
        <SRField label="Website">
          <input style={srInputStyle} value={websiteUrl} onChange={e => setWebsiteUrl(e.target.value)} placeholder="https://..." />
        </SRField>
        <SRField label="Status">
          <select style={srInputStyle} value={status} onChange={e => setStatus(e.target.value)}>
            <option value="active">Active (visible to buyers)</option>
            <option value="contacted">Contacted (sales outreach started)</option>
            <option value="onboarded">Onboarded (now a real Pipal store)</option>
            <option value="archived">Archived (hidden)</option>
          </select>
        </SRField>
        {err && <div style={{ fontSize: 12, color: "var(--neg)", background: "var(--neg-soft)", padding: "8px 10px", borderRadius: 5 }}>{err}</div>}
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" onClick={handleSubmit} disabled={saving}>{saving ? "Saving…" : "Save"}</button>
        </div>
      </div>
    </SRModal>
  );
};

// ── helpers ────────────────────────────────────────────────────────────────────

function srStatusTone(s) {
  return s === "active" ? "pos" : s === "onboarded" ? "accent" : s === "contacted" ? "warn" : "neg";
}

// ── StoreRequestsPage ────────────────────────────────────────────────────────────

const StoreRequestsPage = () => {
  const I = window.Icons;
  const sb = window.supabaseClient;

  const [stores, setStores] = useStateSR([]);
  const [demand, setDemand] = useStateSR({}); // wishlist_store_id -> vote_count
  const [customVotes, setCustomVotes] = useStateSR([]);
  const [referrers, setReferrers] = useStateSR([]); // store_referrers rows
  const [payouts, setPayouts] = useStateSR([]); // matched signups: {store, referrer, payout}
  const [loading, setLoading] = useStateSR(true);
  const [tab, setTab] = useStateSR("curated"); // curated | custom | referrals
  const [modal, setModal] = useStateSR(null); // null | "new" | {row}
  const [deleteTarget, setDeleteTarget] = useStateSR(null);
  const [payingId, setPayingId] = useStateSR(null);

  const fetchAll = async () => {
    setLoading(true);
    const [storesRes, demandRes, customRes, referrersRes, allStoresRes, payoutsRes] = await Promise.all([
      sb.from("wishlist_stores").select("*").order("display_order").order("created_at", { ascending: false }),
      sb.from("wishlist_store_demand").select("id, vote_count"),
      sb.from("store_demand_votes").select("id, custom_name, custom_link, created_at").not("custom_name", "is", null).order("created_at", { ascending: false }),
      sb.from("store_referrers")
        .select("user_id, referral_code, phone, instagram, facebook, created_at")
        .order("created_at", { ascending: false }),
      sb.from("stores").select("id, name, status, settings, created_at"),
      sb.from("store_referral_payouts").select("id, store_id, referral_code, payout_status, payout_amount, paid_at"),
    ]);
    if (storesRes.data) setStores(storesRes.data);
    if (demandRes.data) {
      const m = {};
      demandRes.data.forEach(d => { m[d.id] = d.vote_count; });
      setDemand(m);
    }
    if (customRes.data) setCustomVotes(customRes.data);
    if (referrersRes.data) setReferrers(referrersRes.data);

    if (referrersRes.data && allStoresRes.data) {
      const referrerByCode = {};
      referrersRes.data.forEach(r => { referrerByCode[r.referral_code] = r; });

      const payoutByStoreId = {};
      (payoutsRes.data || []).forEach(p => { payoutByStoreId[p.store_id] = p; });

      const matches = allStoresRes.data
        .map(s => {
          const code = s.settings?.referred_by_code;
          const referrer = code ? referrerByCode[code] : null;
          if (!referrer) return null;
          return {
            store: s,
            referrer,
            payout: payoutByStoreId[s.id] || null,
          };
        })
        .filter(Boolean)
        .sort((a, b) => new Date(b.store.created_at) - new Date(a.store.created_at));
      setPayouts(matches);
    } else {
      setPayouts([]);
    }
    setLoading(false);
  };

  useEffectSR(() => {
    if (!sb) return;
    fetchAll();
  }, []);

  const saveStore = async (payload) => {
    if (modal?.id) {
      const { error } = await sb.from("wishlist_stores").update(payload).eq("id", modal.id);
      if (error) throw new Error(error.message || error.error || JSON.stringify(error));
    } else {
      const { error } = await sb.from("wishlist_stores").insert(payload);
      if (error) throw new Error(error.message || error.error || JSON.stringify(error));
    }
    await fetchAll();
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    await sb.from("wishlist_stores").delete().eq("id", deleteTarget.id);
    setDeleteTarget(null);
    await fetchAll();
  };

  const markPaid = async (match, amount) => {
    setPayingId(match.store.id);
    try {
      const { data: { user } } = await sb.auth.getUser();
      const { error } = await sb.from("store_referral_payouts").upsert({
        store_id: match.store.id,
        referral_code: match.referrer.referral_code,
        payout_status: "paid",
        payout_amount: amount,
        paid_at: new Date().toISOString(),
        paid_by: user?.id ?? null,
      }, { onConflict: "store_id" });
      if (error) throw error;
      await fetchAll();
    } catch (e) {
      alert("Failed to mark paid: " + e.message);
    } finally {
      setPayingId(null);
    }
  };

  const markIneligible = async (match) => {
    setPayingId(match.store.id);
    try {
      const { error } = await sb.from("store_referral_payouts").upsert({
        store_id: match.store.id,
        referral_code: match.referrer.referral_code,
        payout_status: "ineligible",
      }, { onConflict: "store_id" });
      if (error) throw error;
      await fetchAll();
    } catch (e) {
      alert("Failed: " + e.message);
    } finally {
      setPayingId(null);
    }
  };

  const totalVotes = Object.values(demand).reduce((a, b) => a + b, 0) + customVotes.length;
  const unpaidCount = payouts.filter(p => (p.payout?.payout_status || "unpaid") === "unpaid").length;

  return (
    <div className="page" data-screen-label="Store Requests">
      <div className="page-h">
        <div>
          <div className="ts">{loading ? "Loading…" : `${stores.length} curated stores · ${totalVotes} total requests`}</div>
          <h1>Bring to Pipal</h1>
        </div>
        <button className="btn primary" onClick={() => setModal("new")}>
          <I.plus size={11} /> New store
        </button>
      </div>

      <div className="ftabs" style={{ marginBottom: 16 }}>
        <div className={"ftab" + (tab === "curated" ? " active" : "")} onClick={() => setTab("curated")}>
          Curated stores <span className="ct">{stores.length}</span>
        </div>
        <div className={"ftab" + (tab === "custom" ? " active" : "")} onClick={() => setTab("custom")}>
          Custom requests {customVotes.length > 0 && <span className="ct">{customVotes.length}</span>}
        </div>
        <div className={"ftab" + (tab === "referrals" ? " active" : "")} onClick={() => setTab("referrals")}>
          Referral payouts {unpaidCount > 0 && <span className="ct">{unpaidCount}</span>}
        </div>
      </div>

      {tab === "curated" && (
        <div className="panel" style={{ overflow: "hidden" }}>
          <div className="panel-h">
            <span>Curated stores, ranked by demand</span>
          </div>
          {loading ? (
            <div style={{ padding: 24, textAlign: "center", color: "var(--ink-3)", fontSize: 12 }}>Loading…</div>
          ) : stores.length === 0 ? (
            <div style={{ padding: 32, textAlign: "center", color: "var(--ink-3)", fontSize: 12 }}>
              No stores yet. Add the brands/stores you want buyers to vote for.
            </div>
          ) : (
            <div className="t-wrap">
              <table className="t">
                <thead>
                  <tr>
                    <th style={{ width: 40 }}></th>
                    <th>Name</th>
                    <th>Category</th>
                    <th style={{ textAlign: "center" }}>Requests</th>
                    <th style={{ textAlign: "center" }}>Status</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {[...stores].sort((a, b) => (demand[b.id] || 0) - (demand[a.id] || 0)).map(store => (
                    <tr key={store.id}>
                      <td>
                        <div style={{
                          width: 30, height: 30, borderRadius: 6, background: "var(--surface-3)",
                          overflow: "hidden", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12,
                        }}>
                          {store.logo_url
                            ? <img src={store.logo_url} alt={store.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                            : store.name[0]}
                        </div>
                      </td>
                      <td style={{ fontWeight: 500 }}>
                        {store.name}
                        <div style={{ display: "flex", gap: 6, marginTop: 3 }}>
                          {store.instagram_url && <a href={store.instagram_url} target="_blank" rel="noreferrer" style={{ fontSize: 10.5, color: "var(--ink-3)" }}>IG</a>}
                          {store.facebook_url && <a href={store.facebook_url} target="_blank" rel="noreferrer" style={{ fontSize: 10.5, color: "var(--ink-3)" }}>FB</a>}
                          {store.tiktok_url && <a href={store.tiktok_url} target="_blank" rel="noreferrer" style={{ fontSize: 10.5, color: "var(--ink-3)" }}>TikTok</a>}
                          {store.website_url && <a href={store.website_url} target="_blank" rel="noreferrer" style={{ fontSize: 10.5, color: "var(--ink-3)" }}>Web</a>}
                        </div>
                      </td>
                      <td><span style={{ fontSize: 12, color: "var(--ink-2)" }}>{store.category || "—"}</span></td>
                      <td style={{ textAlign: "center" }}><span className="num">{demand[store.id] || 0}</span></td>
                      <td style={{ textAlign: "center" }}>
                        <span className={`chip dot ${srStatusTone(store.status)}`} style={{ fontSize: 10 }}>{store.status}</span>
                      </td>
                      <td>
                        <div style={{ display: "flex", gap: 4, justifyContent: "flex-end" }}>
                          <button className="btn ghost" style={{ height: 22, width: 22, padding: 0, display: "grid", placeItems: "center" }} onClick={() => setModal(store)}>
                            <I.edit size={10} />
                          </button>
                          <button className="btn ghost" style={{ height: 22, width: 22, padding: 0, display: "grid", placeItems: "center", color: "var(--neg)" }} onClick={() => setDeleteTarget(store)}>
                            <I.trash size={10} />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {tab === "custom" && (
        <div className="panel" style={{ overflow: "hidden" }}>
          <div className="panel-h">
            <span>Buyer-typed requests not in the curated list</span>
          </div>
          {customVotes.length === 0 ? (
            <div style={{ padding: 32, textAlign: "center", color: "var(--ink-3)", fontSize: 12 }}>
              No custom requests yet.
            </div>
          ) : (
            <div className="t-wrap">
              <table className="t">
                <thead>
                  <tr>
                    <th>Requested</th>
                    <th>Link</th>
                    <th style={{ textAlign: "right" }}>Date</th>
                  </tr>
                </thead>
                <tbody>
                  {customVotes.map(v => (
                    <tr key={v.id}>
                      <td style={{ fontWeight: 500 }}>{v.custom_name}</td>
                      <td>
                        {v.custom_link
                          ? <a href={v.custom_link} target="_blank" rel="noreferrer" style={{ fontSize: 12, color: "var(--accent)" }}>{v.custom_link}</a>
                          : <span style={{ fontSize: 12, color: "var(--ink-3)" }}>—</span>}
                      </td>
                      <td style={{ textAlign: "right", fontSize: 11.5, color: "var(--ink-3)", fontFamily: "var(--font-mono)" }}>
                        {new Date(v.created_at).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {tab === "referrals" && (
        <>
          <div className="panel" style={{ overflow: "hidden", marginBottom: 14 }}>
            <div className="panel-h">
              <span>Matched signups — Rs. 1000 per store, mark paid once verified active</span>
            </div>
            {payouts.length === 0 ? (
              <div style={{ padding: 32, textAlign: "center", color: "var(--ink-3)", fontSize: 12 }}>
                No seller has entered a referral code yet.
              </div>
            ) : (
              <div className="t-wrap">
                <table className="t">
                  <thead>
                    <tr>
                      <th>Store signed up</th>
                      <th>Referrer contact</th>
                      <th>Code</th>
                      <th style={{ textAlign: "center" }}>Status</th>
                      <th></th>
                    </tr>
                  </thead>
                  <tbody>
                    {payouts.map(match => {
                      const status = match.payout?.payout_status || "unpaid";
                      return (
                        <tr key={match.store.id}>
                          <td style={{ fontWeight: 500 }}>
                            {match.store.name}
                            <span className="chip" style={{ fontSize: 10, marginLeft: 6 }}>{match.store.status}</span>
                          </td>
                          <td>
                            <div style={{ fontSize: 12.5 }}>{match.referrer.phone}</div>
                            <div style={{ display: "flex", gap: 6, marginTop: 2 }}>
                              {match.referrer.instagram && <span style={{ fontSize: 10.5, color: "var(--ink-3)" }}>IG: {match.referrer.instagram}</span>}
                              {match.referrer.facebook && <span style={{ fontSize: 10.5, color: "var(--ink-3)" }}>FB: {match.referrer.facebook}</span>}
                            </div>
                          </td>
                          <td><span className="id" style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{match.referrer.referral_code}</span></td>
                          <td style={{ textAlign: "center" }}>
                            <span className={`chip dot ${status === "paid" ? "pos" : status === "ineligible" ? "neg" : "warn"}`} style={{ fontSize: 10 }}>
                              {status === "paid" ? `paid Rs.${match.payout.payout_amount}` : status}
                            </span>
                          </td>
                          <td>
                            {status === "unpaid" && (
                              <div style={{ display: "flex", gap: 4, justifyContent: "flex-end" }}>
                                <button
                                  className="btn ghost"
                                  style={{ height: 24, fontSize: 11 }}
                                  onClick={() => markIneligible(match)}
                                  disabled={payingId === match.store.id}
                                >Not eligible</button>
                                <button
                                  className="btn primary"
                                  style={{ height: 24, fontSize: 11 }}
                                  onClick={() => markPaid(match, 1000)}
                                  disabled={payingId === match.store.id}
                                >{payingId === match.store.id ? "…" : "Mark paid Rs.1000"}</button>
                              </div>
                            )}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          <div className="panel" style={{ overflow: "hidden" }}>
            <div className="panel-h">
              <span>All opted-in referrers ({referrers.length})</span>
            </div>
            {referrers.length === 0 ? (
              <div style={{ padding: 32, textAlign: "center", color: "var(--ink-3)", fontSize: 12 }}>
                No one has opted into outreach yet.
              </div>
            ) : (
              <div className="t-wrap">
                <table className="t">
                  <thead>
                    <tr>
                      <th>Code</th>
                      <th>Phone</th>
                      <th>Socials</th>
                      <th style={{ textAlign: "right" }}>Since</th>
                    </tr>
                  </thead>
                  <tbody>
                    {referrers.map(r => (
                      <tr key={r.user_id}>
                        <td><span className="id" style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{r.referral_code}</span></td>
                        <td style={{ fontSize: 12.5 }}>{r.phone}</td>
                        <td>
                          <div style={{ display: "flex", gap: 6 }}>
                            {r.instagram && <span style={{ fontSize: 10.5, color: "var(--ink-3)" }}>IG: {r.instagram}</span>}
                            {r.facebook && <span style={{ fontSize: 10.5, color: "var(--ink-3)" }}>FB: {r.facebook}</span>}
                            {!r.instagram && !r.facebook && <span style={{ fontSize: 10.5, color: "var(--ink-3)" }}>—</span>}
                          </div>
                        </td>
                        <td style={{ textAlign: "right", fontSize: 11.5, color: "var(--ink-3)", fontFamily: "var(--font-mono)" }}>
                          {new Date(r.created_at).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </>
      )}

      {modal && (
        <StoreRequestModal
          initial={modal === "new" ? null : modal}
          onSave={saveStore}
          onClose={() => setModal(null)}
        />
      )}

      {deleteTarget && (
        <SRModal title="Confirm delete" onClose={() => setDeleteTarget(null)}>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div style={{ fontSize: 13, color: "var(--ink-2)" }}>
              Delete <strong>{deleteTarget.name}</strong>? This also removes all buyer requests tied to it. This cannot be undone.
            </div>
            <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
              <button className="btn ghost" onClick={() => setDeleteTarget(null)}>Cancel</button>
              <button className="btn" style={{ background: "var(--neg)", color: "#fff", borderColor: "var(--neg)" }} onClick={handleDelete}>Delete</button>
            </div>
          </div>
        </SRModal>
      )}
    </div>
  );
};

window.StoreRequestsPage = StoreRequestsPage;
