"""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 | Starter | Pro |
| :--- | :--- | :--- | :--- |
| **Price** | $0/mo | $49/mo | $149/mo |
| **Projects** | 3 | 10 | Unlimited |
| **Rows** | 5,000 | 50,000 | Unlimited |
| **Channels** | 5 | 15 | Unlimited |
| **Runs/month** | 3 | 20 | Unlimited |
""")

    st.markdown("---")
    st.markdown("### Upgrade")

    tier_rank = {"free": 0, "starter": 1, "pro": 2}
    current_rank = tier_rank.get(current_tier, 0)

    col1, col2 = st.columns(2)

    if current_rank < 1:
        with col1:
            if st.button("Upgrade to Starter", key="btn_starter"):
                resp = api_client.post(
                    "/billing/create-checkout-session", params={"plan": "starter"}
                )
                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"))

    if current_rank < 2:
        with col2:
            if st.button("Upgrade to Pro", 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"))

    if current_rank == 2:
        st.info("You are already on the Pro plan.")
