import streamlit as st
import requests
import pandas as pd
from pathlib import Path
from components.rule_editor import rule_editor
from datetime import datetime

BACKEND_URL = "http://172.17.0.2:3001"

def render_auto_trading_tab(surfaces):
    """Auto Trading Tab — Rules + Portfolio + Recent Trades"""
    st.header("🚀 Auto Trading")

    # Global controls
    colA, colB, colC = st.columns([2, 2, 1])
    with colA:
        if st.button("🔄 Refresh All"):
            st.rerun()

    with colB:
        if st.button("🛠️ Backend Health Check"):
            try:
                r = requests.get(f"{BACKEND_URL}/health", timeout=5)
                st.success(f"Backend OK: {r.status_code}")
            except:
                st.error("Backend unreachable")

    st.divider()
    # === FETCH DATA ===
    @st.cache_data(ttl=10)
    def fetch_aggregated():
        try:
            r = requests.get(f"{BACKEND_URL}/aggregated", timeout=5)
            return r.json()
        except Exception as e:
            st.error(f"Failed to fetch aggregated: {e}")
            return {"aggregated": {}, "total_weight": 0, "token_count": 0}

    @st.cache_data(ttl=5)
    def fetch_portfolio():
        try:
            r = requests.get(f"{BACKEND_URL}/api/portfolio", timeout=5)
            data = r.json()
            return data
        except Exception as e:
            st.error(f"Failed to fetch portfolio: {e}")
            return {"cash": 0.0, "positions": [], "positions_count": 0}

    portfolio = fetch_portfolio()

    cash = portfolio.get("cash", 0.0)
    positions = portfolio.get("positions", [])
    positions_count = portfolio.get("positions_count", 0)
        
    aggregated = fetch_aggregated()
    # 1. RULES LIST
    st.subheader("📋 Active Rules")
    try:
        rules = requests.get(f"{BACKEND_URL}/api/rules").json().get("rules")
    except:
        rules = []

    if not rules:
        st.info("No rules yet. Create one below.")
    else:
        for rule in rules:
            c1, c2, c3, c4 = st.columns([4, 1.5, 1, 1])
            with c1:
                st.write(f"**{rule.get('oname') or rule.get('name')}**")
            with c2:
                enabled = st.toggle("Enabled", value=rule.get("enabled", False), key=f"toggle_{rule['oname']}")
                if enabled != rule.get("enabled", False):
                    requests.post(f"{BACKEND_URL}/api/rules", json={**rule, "enabled": enabled})
                    st.rerun()
            with c3:
                if st.button("✏️ Edit", key=f"edit_{rule['oname']}"):
                    st.session_state.editing_rule = rule
                    st.rerun()
            with c4:
                if st.button("🗑️", key=f"del_{rule['oname']}"):
                    requests.delete(f"{BACKEND_URL}/api/rules/{rule['oname']}")
                    st.rerun()

    if st.button("➕ Create New Rule", type="primary", use_container_width=True):
        st.session_state.editing_rule = {}
        st.rerun()

    # Rule Editor (modal-like)
    if "editing_rule" in st.session_state:
        st.divider()
        st.subheader("📝 Rule Editor")
        result = rule_editor(list(surfaces.keys()), init_data=st.session_state.editing_rule)
        print(result)
        if result and "saved_rule" in result:
            requests.post(f"{BACKEND_URL}/api/rules", json=result["saved_rule"])
            st.success("Rule saved!")
            del st.session_state.editing_rule
            st.rerun()

    st.divider()

    # 2. PORTFOLIO POSITIONS
    # === LAYOUT: TWO COLUMNS ===
    col1, col2 = st.columns(2)

    # ========== LEFT: AGGREGATED (TARGET) ==========
    with col1:
        st.subheader("📊 Target Allocation (Aggregated)")
        
        agg_data = aggregated.get("aggregated", {})
        
        if agg_data:
            df_agg = pd.DataFrame([
                {"Token": token, "Weight": weight, "Weight %": f"{weight*100:.1f}%"}
                for token, weight in sorted(agg_data.items(), key=lambda x: -x[1])
            ])
            st.dataframe(df_agg, use_container_width=True, hide_index=True)
            
            st.metric("Total Weight", f"{aggregated.get('total_weight', 0):.2f}")
            st.metric("Tokens in Target", aggregated.get("token_count", 0))
        else:
            st.info("No aggregated data yet. Run background job first.")

    # ========== RIGHT: ACTUAL PORTFOLIO ==========
    with col2:
        st.subheader("💼 Current Portfolio")
        
        cash = portfolio.get("cash", 0)
        positions = portfolio.get("positions", [])
        
        st.metric("Cash", f"${cash:,.2f}")
        st.metric("Open Positions", len(positions))
        
        if positions:
            df_pos = pd.DataFrame(positions)
            # Show market slugs instead of raw CLOB token IDs (slug already populated by backend sync_portfolio)
            if "slug" in df_pos.columns:
                df_pos = df_pos.rename(columns={"slug": "Market Slug"})
            cols_to_show = ["Market Slug", "amount", "entry_price", "current_price"]
            existing_cols = [c for c in cols_to_show if c in df_pos.columns]
            st.dataframe(df_pos[existing_cols], use_container_width=True, hide_index=True)
        else:
            st.info("No open positions")

    # === REBALANCE BUTTON ===
    st.divider()

    # 3. RECENT TRADES
    st.subheader("📜 Recent Trades")
    try:
        trades = requests.get(f"{BACKEND_URL}/api/trades/recent").json().get("trades", [])
    except:
        trades = []

    for trade in trades[:15]:
        cols = st.columns([2, 2, 2, 2, 2])
        cols[0].write(trade.get("timestamp", "")[:19])
        cols[1].write(trade.get("slug", ""))
        cols[2].write(f"{trade.get('side', '').upper()} {trade.get('amount', 0)}")
        cols[3].write(f"@ {trade.get('price', 0):.4f}")
        cols[4].write(f"PnL: {trade.get('pnl', 0):.2f}")

    st.caption("Auto-refresh every 60s via backend WS job.")