import streamlit as st
import random
import time

# Page Configuration for Premium Dark Theme
st.set_page_config(page_title="AI Trading Tool", layout="wide", initial_sidebar_state="expanded")

# Custom CSS to force Dark Mode & Premium UI
st.markdown("""
    <style>
    .main { background-color: #0d1117; color: #ffffff; }
    .stButton>button { background-color: #238636; color: white; border-radius: 8px; border: none; padding: 10px 24px; font-weight: bold; }
    .stButton>button:hover { background-color: #2ea043; color: white; }
    .news-card { background-color: #161b22; padding: 16px; border-radius: 12px; margin-bottom: 12px; border: 1px solid #30363d; }
    .strategy-card { background-color: #161b22; padding: 12px; border-radius: 8px; margin-bottom: 8px; border-left: 4px solid #238636; }
    .badge-high { background-color: #da3637; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold; }
    .badge-medium { background-color: #d29922; color: black; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold; }
    .badge-low { background-color: #238636; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold; }
    .growth-green { color: #3fb950; font-weight: bold; }
    .growth-red { color: #f85149; font-weight: bold; }
    </style>
""", unsafe_allowed_value=True)

# Top Navigation Bar
st.title("📈 Deeepr AI Clone - Premium Trading Dashboard")
top_tab = st.radio("Navigation", ["News Terminal", "Strategy Builder & Backtester"], horizontal=True, label_visibility="collapsed")

st.markdown("---")

# ----------------- PAGE 1: NEWS TERMINAL -----------------
if top_tab == "News Terminal":
    st.subheader("📰 Market Impact News Terminal")
    news_filter = st.segmented_control("Select Asset Filter", ["Crypto Impact", "Metal Impact", "Forex Impact"], default="Crypto Impact")
    
    st.write("")
    if news_filter == "Crypto Impact":
        st.markdown('<div class="news-card"><h4>US SEC Approves New Crypto Index Fund</h4><p>Massive institutional volume expected in the coming weeks. Price volatility expected.</p><span class="badge-high">HIGH IMPACT</span> <span style="color:#8b949e; font-size:12px;">• 5m ago</span></div>', unsafe_allowed_html=True)
        st.markdown('<div class="news-card"><h4>Bitcoin Hashrate Hits New All-Time High</h4><p>Network security strengthens as miners upgrade hardware globally.</p><span class="badge-low">LOW IMPACT</span> <span style="color:#8b949e; font-size:12px;">• 25m ago</span></div>', unsafe_allowed_html=True)
    elif news_filter == "Metal Impact":
        st.markdown('<div class="news-card"><h4>Gold Hits New Record High Amid Global Inflation Concerns</h4><p>Investors flock to safe-haven assets as fiat currencies weaken.</p><span class="badge-high">HIGH IMPACT</span> <span style="color:#8b949e; font-size:12px;">• 12m ago</span></div>', unsafe_allowed_html=True)
        st.markdown('<div class="news-card"><h4>Silver Mining Supply Facing Deficit in 2026</h4><p>Industrial demand for solar panels pushing physical silver reserves to the limit.</p><span class="badge-medium">MEDIUM IMPACT</span> <span style="color:#8b949e; font-size:12px;">• 1h ago</span></div>', unsafe_allowed_html=True)
    elif news_filter == "Forex Impact":
        st.markdown('<div class="news-card"><h4>Fed Hints at Interest Rate Cuts Next Month</h4><p>US Dollar Index (DXY) slips below key support level. EUR/USD spikes.</p><span class="badge-high">HIGH IMPACT</span> <span style="color:#8b949e; font-size:12px;">• 2m ago</span></div>', unsafe_allowed_html=True)

# ----------------- PAGE 2: STRATEGY BUILDER -----------------
else:
    # Sidebar Layout & Main Layout Split
    col_left, col_right = st.columns([1, 3])
    
    with col_left:
        st.markdown("### 🗂️ Strategies")
        strat_status = st.tabs(["Drafts", "Saved", "Live"])
        
        with strat_status[0]:
            st.caption("No drafts yet. Type on the right to start!")
            
        with strat_status[1]:
            st.markdown('<div class="strategy-card"><b>RSI Overbought/Oversold</b><br><small>W1: <span class="growth-green">+3.2%</span> | W2: <span class="growth-green">+1.5%</span><br>W3: <span class="growth-red">-0.8%</span> | W4: <span class="growth-green">+4.1%</span></small></div>', unsafe_allowed_html=True)
            st.markdown('<div class="strategy-card"><b>EMA Golden Cross 50/20</b><br><small>W1: <span class="growth-green">+0.5%</span> | W2: <span class="growth-green">+2.1%</span><br>W3: <span class="growth-green">+1.8%</span> | W4: <span class="growth-red">-1.2%</span></small></div>', unsafe_allowed_html=True)
            
        with strat_status[2]:
            st.success("🟢 1 Strategy Running Live")
            st.markdown('<div style="background-color:#1f2937; padding:10px; border-radius:5px;"><b>BTC Breakout Hunter v2</b><br><small style="color:#3fb950;">Active & Monitoring Market</small></div>', unsafe_allowed_html=True)
            
    with col_right:
        # Header Controls
        c1, c2 = st.columns([3, 1])
        with c1:
            st.subheader("🤖 Create Custom AI Trading Strategy")
        with c2:
            paper_trade = st.toggle("Paper Trading Mode", value=False)
            if paper_trade:
                st.toast("🦁 Paper Trading Mode Active (Virtual Money)")
        
        # Natural Language Input
        user_input = st.text_area(
            "اپنی حکمت عملی یہاں لکھیں (Describe your strategy in your language):", 
            placeholder="Example: Buy Bitcoin when RSI crosses below 30, and Sell when it goes above 70..."
        )
        
        # Backtest Action Button
        if st.button("🚀 Run Backtest & Analyze"):
            if user_input.strip() == "":
                st.warning("Please type a strategy first!")
            else:
                with st.spinner("AI parsing your language and fetching backtest data..."):
                    time.sleep(2.5) # Simulating AI processing
                st.success("Analysis Complete!")
                
                # Mock Results Dashboard
                stat_col1, stat_col2, stat_col3 = st.columns(3)
                stat_col1.metric("Total Win Rate", "64.2%", "+2.3%")
                stat_col2.metric("Profit Factor", "1.85", "Optimal")
                stat_col3.metric("Net Return", "+18.4%", "Based on 30-day data")
                
                # Dynamic Message
                st.info(f"AI Logic Parsed Successfully: Applied condition for strategy on current chart.")
        
        # Telegram Integration Settings Expansion
        with st.expander("✈️ Telegram Alerts & Notification Settings"):
            st.info("When your strategy triggers a BUY/SELL, it will automatically text your phone via Telegram!")
            bot_token = st.text_input("Telegram Bot Token", type="password", placeholder="1234567890:ABCdefGhIJKlmNoPQRsTUVwxyZ")
            chat_id = st.text_input("Telegram Chat ID", placeholder="987654321")
            if bot_token and chat_id:
                st.success("✅ Telegram configurations saved for this session.")
