# frontend/tabs/signals.py
import streamlit as st
import plotly.graph_objects as go
import pandas as pd
import requests
from datetime import datetime, timezone
from zoneinfo import ZoneInfo

BACKEND_URL = "http://172.17.0.2:3001"

def render_signals_tab(selected_slug: str):
    st.subheader("📈 Trading Signals — Smart XTracker View")

    if not selected_slug:
        st.error("No event selected")
        return

    # Fetch from backend
    try:
        resp = requests.get(f"{BACKEND_URL}/api/xtracker/{selected_slug}", timeout=15)
        if resp.status_code != 200:
            st.error(f"Backend error: {resp.status_code}")
            return
        data = resp.json()
    except Exception as e:
        st.error(f"Failed to connect to backend: {e}")
        return

    # === Extract data ===
    current_count = data.get("current_count", 0)
    remaining_hours = data.get("remaining_hours", 0)
    pace_24h = data.get("pace_24h", 0)
    pace_7d = data.get("pace_7d", 0)
    pace_30d = data.get("pace_30d", 0)
    avg_pace = data.get("avg_pace", 0)

    projected_24h = data.get("projected_24h", 0)
    projected_7d = data.get("projected_7d", 0)
    projected_30d = data.get("projected_30d", 0)
    projected_avg = data.get("projected_avg", 0)

    graph = data.get("graph", {})
    timestamps = graph.get("timestamps", [])
    count_line = graph.get("count_line", [])
    game_start_ts = graph.get("game_start", 0)

    global_heat_10m = data.get("global_heat_10m", [])
    global_heat_4h = data.get("global_heat_4h", [])

    now = datetime.now(timezone.utc)
    game_start = datetime.fromtimestamp(game_start_ts, tz=timezone.utc)
    has_started = now >= game_start

    # ====================== SMART PROJECTIONS ======================
    if not has_started:
        # Future event → use full duration projections
        total_hours = 7 * 24  # assume 7-day event (you can make this dynamic later)
        st.info(f"⏳ Event starts in {(game_start - now).days} days")
        
        proj_24h = pace_24h * total_hours
        proj_7d = pace_7d * total_hours
        proj_30d = pace_30d * total_hours
        proj_avg = avg_pace * total_hours
    else:
        proj_24h = projected_24h
        proj_7d = projected_7d
        proj_30d = projected_30d
        proj_avg = projected_avg

    # ====================== METRICS ======================
    col1, col2, col3, col4 = st.columns(4)
    with col1: st.metric("Current Count", current_count)
    with col2: st.metric("24h Projection", f"{proj_24h:.0f}")
    with col3: st.metric("7d Projection", f"{proj_7d:.0f}")
    with col4: st.metric("Remaining Hours", f"{remaining_hours:.1f}")

    # ====================== GRAPH ======================
    fig = go.Figure()

    # Add heat lines (always show)
    if global_heat_10m:
        df_10m = pd.DataFrame(global_heat_10m, columns=["ts", "count"])
        df_10m["time"] = pd.to_datetime(df_10m["ts"], unit="s", utc=True).dt.tz_convert("Europe/Berlin")
        fig.add_scatter(x=df_10m["time"], y=df_10m["count"], name="Heat 10m", line=dict(color="blue", width=1.5))

    if global_heat_4h:
        df_4h = pd.DataFrame(global_heat_4h, columns=["ts", "count"])
        df_4h["time"] = pd.to_datetime(df_4h["ts"], unit="s", utc=True).dt.tz_convert("Europe/Berlin")
        fig.add_scatter(x=df_4h["time"], y=df_4h["count"], name="Heat 4h", line=dict(color="lightblue", width=2))

    # Add count_line only if event has started
    if has_started and timestamps and count_line:
        df_count = pd.DataFrame({"ts": timestamps, "count": count_line})
        df_count["time"] = pd.to_datetime(df_count["ts"], unit="s", utc=True).dt.tz_convert("Europe/Berlin")
        fig.add_scatter(x=df_count["time"], y=df_count["count"], name="Cumulative Count", line=dict(color="#EF553B", width=3))

    # Auto-zoom logic
    if has_started:
        fig.update_xaxes(range=[game_start, now])
    else:
        # Show last 14 days of heat data before start
        fig.update_xaxes(range=[game_start - pd.Timedelta(days=14), game_start + pd.Timedelta(days=2)])

    fig.update_layout(
        height=520,
        title="Global Heat Lines + Count (auto-zoomed)",
        xaxis_title="Time (Berlin)",
        yaxis_title="Count / Heat",
        legend=dict(yanchor="top", y=0.99, xanchor="left", x=0.01)
    )
    st.plotly_chart(fig, use_container_width=True)

    # ====================== PACE ======================
    st.subheader("Pace & Projections")
    col1, col2, col3, col4 = st.columns(4)
    with col1: st.metric("24h Pace", f"{pace_24h:.2f}/h")
    with col2: st.metric("7d Pace", f"{pace_7d:.2f}/h")
    with col3: st.metric("30d Pace", f"{pace_30d:.2f}/h")
    with col4: st.metric("AVG Pace", f"{avg_pace:.2f}/h")

    # ====================== RAW DATA ======================
    with st.expander("Raw Backend Data"):
        st.json(data)
