"""Billing page: plan comparison and upgrade."""

import streamlit as st

from frontend import api_client


def show_billing_page():
    if st.button("< Back to Dashboard"):
        st.session_state["page"] = "dashboard"
        st.rerun()

    st.title("Billing & Plans")

    # Check query params for post-checkout status
    query_params = st.query_params
    if "billing" in query_params:
        billing_status = query_params["billing"]
        if billing_status == "success":
            st.success("Payment successful! Your plan has been upgraded.")
        elif billing_status == "cancel":
            st.warning("Payment was cancelled. Please try again if you wish to upgrade.")

    # Fetch current tier
    current_tier = "free"
    resp = api_client.get("/auth/me")
    if resp.status_code == 200:
        current_tier = resp.json().get("tier", "free")

    st.subheader(f"Current Plan: **{current_tier.capitalize()}**")

    st.markdown("### Plan Comparison")
    st.markdown("""
| Feature | Free | Growth |
| :--- | :--- | :--- |
| **Price** | $0/mo | $299/mo |
| **Channels** | 2 | 8 |
| **Rows** | 2,000 | 50,000 |
| **Runs/month** | 2 | Unlimited |
| **Dollar headlines** | No | Yes |
| **Scenario mode** | No | Yes |
""")

    st.markdown("---")

    if current_tier == "free":
        st.markdown("### Upgrade to Growth")
        if st.button("Upgrade to Growth — $299/mo", key="btn_pro"):
            resp = api_client.post(
                "/billing/create-checkout-session", params={"plan": "pro"}
            )
            if resp.status_code == 200:
                url = resp.json().get("checkout_url")
                if url:
                    st.markdown(
                        f"<a href='{url}' target='_blank'>Click here to complete payment</a>",
                        unsafe_allow_html=True,
                    )
            else:
                st.error(resp.json().get("detail", "Failed to create checkout session"))
    else:
        st.info("You are on the Growth plan.")
