"""
ui/trending_page.py
- Feature 3: Trending videos daily/weekly
"""

import streamlit as st
import pandas as pd
from datetime import datetime, timedelta
from core.youtube_api import get_trending_videos, get_video_categories
from core.database import save_entry


def render_trending():
    st.subheader("🔥 Feature 3 — Trending Videos")
    st.caption("See what's trending on YouTube right now")

    col1, col2, col3 = st.columns([1, 1, 2])
    region = col1.selectbox(
        "Region",
        ["US", "KH", "TH", "VN", "GB", "IN", "JP", "KR", "FR", "DE"],
        index=0,
    )

    cats = [{"id": "0", "title": "All Categories"}] + get_video_categories(region)
    cat_map = {c["title"]: c["id"] for c in cats}
    cat = col2.selectbox("Category", list(cat_map.keys()), index=0)

    max_n = col3.slider("How many?", 10, 50, 25, step=5)

    if st.button("🔄 Fetch Trending", use_container_width=True):
        with st.spinner("Fetching trending..."):
            try:
                vids = get_trending_videos(region, cat_map[cat], max_n)
            except Exception as e:
                st.error(f"Error: {e}")
                return
        st.session_state.trending_vids = vids
        st.session_state.trending_meta = {"region": region, "category": cat}
        save_entry("trending", f"{region} / {cat}", {"videos": vids})

    vids = st.session_state.get("trending_vids")
    if not vids:
        return

    st.success(f"✅ {len(vids)} trending videos")

    # Table
    df = pd.DataFrame([
        {
            "#": i + 1,
            "Title": v["title"],
            "Channel": v["channel"],
            "Views": v["views_fmt"],
            "Likes": v["likes_fmt"],
            "Duration": v["duration"],
            "Published": v["published_at"][:10],
            "URL": v["url"],
        }
        for i, v in enumerate(vids)
    ])
    st.dataframe(df, use_container_width=True, hide_index=True, height=400)

    # Cards
    st.markdown("---")
    for i, v in enumerate(vids):
        with st.container(border=True):
            c1, c2 = st.columns([1, 3])
            with c1:
                if v.get("thumbnail"):
                    st.image(v["thumbnail"], use_container_width=True)
            with c2:
                st.markdown(f"### #{i+1} — {v['title']}")
                st.caption(f"{v['channel']} • {v['published_at'][:10]}")
                m1, m2, m3 = st.columns(3)
                m1.metric("👁 Views", v["views_fmt"])
                m2.metric("👍 Likes", v["likes_fmt"])
                m3.metric("⏱", v["duration"])
                with st.expander("▶ Play"):
                    st.video(v["url"])

    # Download CSV
    csv_bytes = df.to_csv(index=False).encode("utf-8-sig")
    st.download_button("⬇️ Download CSV", csv_bytes,
                       file_name=f"trending_{region}.csv", mime="text/csv")