"""
ui/channel_page.py
- Feature 6: Channel Analyzer
"""

import streamlit as st
import pandas as pd
import plotly.express as px
from core.youtube_channel import resolve_channel, get_recent_videos, analyze_channel
from core.database import save_entry


def render_channel():
    st.subheader("📈 Channel Analyzer")
    st.caption("Analyze any YouTube channel — subs, videos, upload pattern, top content")

    col1, col2 = st.columns([3, 1])
    url = col1.text_input(
        "Channel URL or @handle or Channel ID",
        placeholder="https://youtube.com/@MrBeast  OR  UCX6OQ3DkcsbYNE6H8uQQuVA",
        key="ch_input",
    )
    max_videos = col2.slider("Videos to fetch", 10, 50, 30, step=10, key="ch_max")

    if st.button("🔍 Analyze Channel", use_container_width=True, key="ch_btn"):
        if not url.strip():
            st.warning("Please enter a channel URL or ID")
            return

        with st.spinner("Resolving channel..."):
            channel = resolve_channel(url)
        if not channel:
            st.error("❌ Channel not found")
            return

        with st.spinner(f"Fetching {max_videos} recent videos..."):
            videos = get_recent_videos(
                channel["id"], channel["uploads_playlist"], max_videos
            )

        with st.spinner("Analyzing..."):
            stats = analyze_channel(channel, videos)

        save_entry("channel", channel["title"],
                   {"channel": channel, "videos": videos, "stats": stats},
                   url=f"https://youtube.com/channel/{channel['id']}")
        st.session_state.channel_result = {
            "channel": channel, "videos": videos, "stats": stats
        }
        st.rerun()

    res = st.session_state.get("channel_result")
    if not res:
        return
    _render(res["channel"], res["videos"], res["stats"])


def _render(channel, videos, stats):
    st.markdown("---")

    # Channel header
    c1, c2 = st.columns([1, 3])
    with c1:
        if channel.get("thumbnail"):
            st.image(channel["thumbnail"], width=150)
    with c2:
        st.markdown(f"## {channel['title']}")
        if channel.get("custom_url"):
            st.caption(f"@{channel['custom_url'].lstrip('@')}")
        st.markdown(channel.get("description", "")[:250])
        if channel.get("country"):
            st.caption(f"🌍 {channel['country']}")

    st.markdown("---")

    # Metrics
    m1, m2, m3, m4 = st.columns(4)
    m1.metric("👥 Subscribers", channel["subs_fmt"] if not channel["hidden_subs"] else "Hidden")
    m2.metric("👁 Total Views", channel["views_fmt"])
    m3.metric("🎬 Videos", channel["videos_fmt"])
    m4.metric("📊 Avg Views/Video", channel["avg_views_fmt"])

    if stats.get("total_analyzed", 0) == 0:
        st.info("No recent videos found")
        return

    m5, m6, m7, m8 = st.columns(4)
    m5.metric("📅 Upload Frequency",
              f"{stats['upload_freq_days']} days" if stats["upload_freq_days"] else "—")
    m6.metric("💯 Avg Engagement", f"{stats['avg_engagement']}%")
    m7.metric("📊 Total Likes (recent)", f"{stats['total_likes']:,}")
    m8.metric("💬 Total Comments", f"{stats['total_comments']:,}")

    # Tabs
    t1, t2, t3, t4 = st.tabs([
        "🏆 Top Videos", "📅 Upload Pattern", "🏷 Tags", "📋 All Videos"
    ])

    with t1:
        st.markdown("### 🏆 Top 10 by Views")
        df = pd.DataFrame([{
            "#": i + 1, "Title": v["title"][:60],
            "Views": v["views_fmt"], "Likes": v["likes_fmt"],
            "Comments": v["comments_fmt"],
        } for i, v in enumerate(stats["top_by_views"])])
        st.dataframe(df, use_container_width=True, hide_index=True)

        # Chart
        fig = px.bar(
            x=[v["views_fmt"] for v in stats["top_by_views"][:10]],
            y=[v["title"][:30] for v in stats["top_by_views"][:10]],
            orientation="h",
            labels={"x": "Views", "y": ""},
            title="Top Videos by Views",
        )
        fig.update_layout(height=400, yaxis=dict(autorange="reversed"))
        st.plotly_chart(fig, use_container_width=True)

    with t2:
        c1, c2 = st.columns(2)
        with c1:
            st.markdown("### 📅 Upload by Day")
            df = pd.DataFrame(stats["top_days"], columns=["Day", "Count"])
            if not df.empty:
                fig = px.bar(df, x="Day", y="Count", color="Count",
                             color_continuous_scale="purples")
                st.plotly_chart(fig, use_container_width=True)
        with c2:
            st.markdown("### 🕐 Upload by Hour")
            df = pd.DataFrame(stats["top_hours"], columns=["Hour", "Count"])
            if not df.empty:
                df["Hour"] = df["Hour"].apply(lambda x: f"{x:02d}:00")
                fig = px.bar(df, x="Hour", y="Count", color="Count",
                             color_continuous_scale="oranges")
                st.plotly_chart(fig, use_container_width=True)

        st.info(f"📊 Average upload: every **{stats['upload_freq_days']} days**"
                if stats.get("upload_freq_days") else "Not enough data")

    with t3:
        st.markdown("### 🏷 Most Used Tags")
        if stats["top_tags"]:
            df = pd.DataFrame(stats["top_tags"], columns=["Tag", "Count"])
            st.dataframe(df, use_container_width=True, hide_index=True)
            st.code(", ".join([t for t, _ in stats["top_tags"]]), language=None)
        else:
            st.info("No tags found")

    with t4:
        st.markdown(f"### 📋 All {len(videos)} Recent Videos")
        df = pd.DataFrame([{
            "Title": v["title"],
            "Published": v["published_at"][:10],
            "Views": v["views"],
            "Likes": v["likes"],
            "Comments": v["comments"],
            "URL": f"https://youtube.com/watch?v={v['id']}",
        } for v in videos])
        st.dataframe(df, use_container_width=True, hide_index=True, height=500)
        st.download_button(
            "⬇️ Download CSV",
            df.to_csv(index=False).encode("utf-8-sig"),
            file_name=f"channel_{channel['id']}.csv",
            mime="text/csv",
        )