// ============================================================================
// public/screens/pricing.jsx — Plans & Billing (Phase 7D)
// ============================================================================

function PricingScreen() {
  const [plans, setPlans]   = React.useState(null);
  const [sub, setSub]       = React.useState(null);
  const [usage, setUsage]   = React.useState(null);
  const [invoices, setInv]  = React.useState(null);
  const [tab, setTab]       = React.useState("plan"); // plan | invoices | payment

  React.useEffect(() => {
    VoaisAPI.get("/api/billing/plans").then(r => { if (r.ok) setPlans(r.data.plans); });
    VoaisAPI.get("/api/billing/subscription").then(r => { if (r.ok) setSub(r.data.subscription); });
    VoaisAPI.get("/api/billing/usage").then(r => { if (r.ok) setUsage(r.data); });
    VoaisAPI.get("/api/billing/invoices").then(r => { if (r.ok) setInv(r.data.invoices); });
  }, []);

  const upgrade = async (code) => {
    if (!confirm("Switch to " + code + " plan?")) return;
    const r = await VoaisAPI.post("/api/billing/subscribe", { plan_code: code });
    if (r.ok) { alert(r.data.msg); location.reload(); }
    else alert(r.data?.msg || "Failed.");
  };

  if (!plans) return <DashboardSkeleton/>;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
      <Tabs value={tab} onChange={setTab} options={[
        { value: "plan", label: "Plan & Usage" }, { value: "invoices", label: "Invoices" }, { value: "payment", label: "Payment" },
      ]}/>

      {tab === "plan" && (<>
        {/* Current plan */}
        {sub && (
          <Card>
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12, color: "var(--ink-3)" }}>Current plan</div>
                <div style={{ fontSize: 22, fontWeight: 700 }}>{sub.plan_name}</div>
                <Badge tone={sub.status === "active" ? "green" : sub.status === "trialing" ? "blue" : "yellow"} dot>{sub.status}</Badge>
              </div>
              <div style={{ textAlign: "right" }}>
                <div style={{ fontSize: 28, fontWeight: 700 }}>{sub.price_inr ? "₹" + Number(sub.price_inr).toLocaleString("en-IN") : "Custom"}</div>
                <div style={{ fontSize: 12, color: "var(--ink-3)" }}>/month</div>
              </div>
            </div>
            {sub.trial_ends_at && sub.status === "trialing" && (
              <div style={{ marginTop: 10, fontSize: 12, color: "var(--warn)" }}>Trial ends: {new Date(sub.trial_ends_at).toLocaleDateString("en-IN")}</div>
            )}
          </Card>
        )}

        {/* Usage meters */}
        {usage && sub && (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 10 }}>
            <UsageMeter label="Minutes" used={usage.current.minutes_used} total={sub.minutes_included} unit="min"/>
            <UsageMeter label="Contacts" used={usage.current.contacts} total={sub.contacts_included}/>
            <UsageMeter label="Agents" used={usage.current.agents} total={sub.agents_included}/>
            <UsageMeter label="Campaigns" used={usage.current.campaigns} total={sub.campaigns_included}/>
            <UsageMeter label="Team members" used={usage.current.users} total={sub.users_included}/>
          </div>
        )}

        {/* Plan comparison */}
        <div style={{ fontSize: 16, fontWeight: 600, marginTop: 8 }}>Available plans</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 12 }}>
          {plans.map(p => {
            const isCurrent = sub?.plan_code === p.code;
            return (
              <Card key={p.id} padded={false} style={{ border: p.popular ? "2px solid var(--accent)" : undefined }}>
                {p.popular && <div style={{ background: "var(--accent)", color: "#fff", textAlign: "center", fontSize: 11, fontWeight: 600, padding: "4px 0" }}>Most popular</div>}
                <div style={{ padding: 16 }}>
                  <div style={{ fontSize: 16, fontWeight: 600 }}>{p.name}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{p.tagline}</div>
                  <div style={{ fontSize: 28, fontWeight: 700, marginTop: 12 }}>{p.price_inr ? "₹" + Number(p.price_inr).toLocaleString("en-IN") : "Custom"}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)" }}>/month</div>
                  <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 6, fontSize: 12 }}>
                    <div>{p.minutes_included.toLocaleString("en-IN")} minutes</div>
                    <div>{p.contacts_included.toLocaleString("en-IN")} contacts</div>
                    <div>{p.agents_included} agents · {p.concurrent_calls} concurrent calls</div>
                    {(p.features || []).slice(0, 4).map((f, i) => <div key={i} style={{ color: "var(--ink-3)" }}>{f}</div>)}
                  </div>
                  <div style={{ marginTop: 14 }}>
                    {isCurrent ? <Btn kind="ghost" size="sm" style={{ width: "100%" }} disabled>Current plan</Btn>
                     : <Btn kind="primary" size="sm" style={{ width: "100%" }} onClick={() => upgrade(p.code)}>
                       {sub && Number(p.price_inr) > Number(sub.price_inr) ? "Upgrade" : "Switch"}</Btn>}
                  </div>
                </div>
              </Card>
            );
          })}
        </div>
      </>)}

      {tab === "invoices" && (<Card padded={false}>
        <table className="data-table" style={{ width: "100%", fontSize: 13 }}>
          <thead><tr><th style={{paddingLeft:16}}>Invoice</th><th>Period</th><th>Amount</th><th>Status</th><th>Date</th></tr></thead>
          <tbody>
            {(invoices || []).map(inv => (
              <tr key={inv.id}>
                <td style={{paddingLeft:16,fontWeight:500}}>{inv.invoice_number}</td>
                <td style={{fontSize:11}}>{inv.period_start?.slice(0,10)} — {inv.period_end?.slice(0,10)}</td>
                <td className="tabular" style={{fontWeight:600}}>₹{Number(inv.total_inr).toLocaleString("en-IN")}</td>
                <td><Badge tone={inv.status==="paid"?"green":inv.status==="overdue"?"red":"gray"}>{inv.status}</Badge></td>
                <td style={{fontSize:11,color:"var(--ink-3)"}}>{inv.issued_at ? new Date(inv.issued_at).toLocaleDateString("en-IN") : "—"}</td>
              </tr>
            ))}
            {(!invoices || invoices.length === 0) && <tr><td colSpan={5} style={{textAlign:"center",padding:32,color:"var(--ink-3)"}}>No invoices yet.</td></tr>}
          </tbody>
        </table>
      </Card>)}

      {tab === "payment" && (<Card>
        <div style={{ padding: 24, textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>
          Payment method management will be available once Razorpay integration is configured.
          Currently billing is managed manually.
        </div>
      </Card>)}
    </div>
  );
}

function UsageMeter({ label, used, total, unit }) {
  const pct = total > 0 ? Math.min(100, Math.round((used / total) * 100)) : 0;
  const over = used > total && total > 0;
  return (
    <div style={{ padding: "12px 14px", background: "var(--surface-2)", borderRadius: 10 }}>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 6 }}>
        <span style={{ color: "var(--ink-3)" }}>{label}</span>
        <span style={{ fontWeight: 600, color: over ? "var(--err)" : "var(--ink-1)" }}>{used}{unit ? " " + unit : ""} / {total || "∞"}</span>
      </div>
      <div style={{ height: 6, background: "var(--surface)", borderRadius: 3, overflow: "hidden" }}>
        <div style={{ height: "100%", width: (total > 0 ? pct : 0) + "%", background: over ? "var(--err)" : pct > 80 ? "var(--warn)" : "var(--accent)", borderRadius: 3, transition: "width 0.5s" }}/>
      </div>
    </div>
  );
}

window.PricingScreen = PricingScreen;
