import streamlit as st
import requests
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from streamlit.components.v1 import html

st.set_page_config(page_title="StarTech Solutions", layout="wide")


st.markdown(
    """
    <style>
    .main {
        background-image: url('background.jpg');
        background-size: cover;
        background-position: center;
        background-attachment: fixed;
        color: white;
    }
    h1, h2, h3 {
        font-family: 'Orbitron', sans-serif;
        color: #00ffcc;
        text-shadow: 0 0 10px #00ffcc;
    }
    .stButton>button {
        background-color: #00ffcc;
        color: #0a0a23;
        border-radius: 25px;
        padding: 0.5rem 1rem;
        font-weight: bold;
    }
    .stTextInput>div>input {
        background-color: rgba(255, 255, 255, 0.1);
        color: white;
        border-radius: 5px;
    }
    table {
        background-color: rgba(255, 255, 255, 0.1);
        border-radius: 10px;
    }
    th {
        background-color: #00ffcc;
        color: #0a0a23;
    }
    td {
        color: white;
    }
    </style>
    """,
    unsafe_allow_html=True
)

s
three_js_html = """
<!DOCTYPE html>
<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
</head>
<body>
    <div id="container" style="width:100%;height:400px;"></div>
    <script>
        const scene = new THREE.Scene();
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth/400, 0.1, 1000);
        const renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth > 768 ? 600 : window.innerWidth-40, 400);
        document.getElementById('container').appendChild(renderer.domElement);

        // Sphere (Satellite)
        const sphereGeometry = new THREE.SphereGeometry(1, 32, 32);
        const sphereMaterial = new THREE.MeshBasicMaterial({color: 0x00ffcc, wireframe: true});
        const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
        scene.add(sphere);

        // Cube (Second Satellite)
        const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
        const cubeMaterial = new THREE.MeshBasicMaterial({color: 0xff00ff, wireframe: true});
        const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
        cube.position.x = 3;
        scene.add(cube);

        camera.position.z = 5;

        function animate() {
            requestAnimationFrame(animate);
            sphere.rotation.y += 0.01;
            cube.rotation.x += 0.01;
            cube.rotation.y += 0.01;
            renderer.render(scene, camera);
        }
        animate();
    </script>
</body>
</html>
"""


page = st.sidebar.selectbox("Navigate", ["Home", "About", "Dashboard", "Contact"])


API_BASE_URL = "http://localhost:8000"


def fetch_missions():
    try:
        response = requests.get(f"{API_BASE_URL}/api/missions")
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        st.error(f"Error fetching missions: {e}")
        return []

def fetch_telemetry():
    try:
        response = requests.get(f"{API_BASE_URL}/api/telemetry")
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        st.error(f"Error fetching telemetry: {e}")
        return {"labels": [], "data": []}

def fetch_mission_detail(index):
    try:
        response = requests.get(f"{API_BASE_URL}/api/missions/{index}")
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        st.error(f"Error fetching mission details: {e}")
        return None


if page == "Home":
    st.title("Revolutionizing Space Exploration")
    st.write("Empowering the future with real-time space data and cutting-edge technology.")
    if st.button("Explore Data"):
        st.session_state.page = "Dashboard"
        st.rerun()


elif page == "About":
    st.title("About StarTech")
    st.write("StarTech Solutions is dedicated to advancing space exploration through innovative satellite technology and real-time data analytics. Our mission is to make space accessible and actionable for all.")
    st.subheader("Key Milestones")
    st.markdown("""
    - **2023**: Launched first AI-powered satellite.
    - **2024**: Partnered with global space agencies.
    - **2025**: Deployed real-time orbital tracking API.
    """)


elif page == "Dashboard":
    st.title("Real-Time Dashboard")

   
    st.subheader("Satellite Telemetry")
    telemetry = fetch_telemetry()
    if telemetry["labels"]:
        fig = px.line(x=telemetry["labels"], y=telemetry["data"], title="Altitude (km)", labels={"x": "Time", "y": "Altitude"})
        fig.update_layout(plot_bgcolor="rgba(0,0,0,0)", paper_bgcolor="rgba(0,0,0,0)", font_color="white")
        st.plotly_chart(fig)

    
    st.subheader("Temperature Data")
    temp_data = {"labels": telemetry["labels"], "data": [x - 50 for x in telemetry["data"]]}  # Mock offset
    fig_temp = px.line(x=temp_data["labels"], y=temp_data["data"], title="Temperature (°C)", labels={"x": "Time", "y": "Temperature"})
    fig_temp.update_layout(plot_bgcolor="rgba(0,0,0,0)", paper_bgcolor="rgba(0,0,0,0)", font_color="white")
    st.plotly_chart(fig_temp)

    
    st.subheader("Orbital Path (3D)")
    df = pd.DataFrame({
        "x": [i for i in range(10)],
        "y": [i**2 for i in range(10)],
        "z": [i**3 % 100 for i in range(10)]
    })
    fig_3d = px.scatter_3d(df, x="x", y="y", z="z", title="Satellite Orbital Path")
    fig_3d.update_layout(scene=dict(bgcolor="rgba(0,0,0,0)"), paper_bgcolor="rgba(0,0,0,0)", font_color="white")
    st.plotly_chart(fig_3d)

    
    st.subheader("3D Satellite Models")
    html(three_js_html, height=400)

    
    st.subheader("Mission Logs")
    search_term = st.text_input("Search logs", "")
    missions = fetch_missions()
    if missions:
        df = pd.DataFrame(missions)
        if search_term:
            df = df[df.apply(lambda row: search_term.lower() in str(row).lower(), axis=1)]
        st.dataframe(df, use_container_width=True)
        selected = st.selectbox("Select mission for details", options=[f"{m['mission']} ({m['date']})" for m in missions], index=0)
        if selected:
            index = [i for i, m in enumerate(missions) if f"{m['mission']} ({m['date']})" == selected][0]
            details = fetch_mission_detail(index)
            if details:
                st.write(f"**Details for {details['mission']}**")
                st.write(f"Date: {details['date']}")
                st.write(f"Status: {details['status']}")
                st.write(f"Description: {details['description']}")

# Contact Page
elif page == "Contact":
    st.title("Contact Us")
    with st.form("contact_form"):
        name = st.text_input("Name", key="name")
        email = st.text_input("Email", key="email")
        message = st.text_input("Message", key="message")
        submitted = st.form_submit_button("Send")
        if submitted:
            try:
                response = requests.post(f"{API_BASE_URL}/api/contact", json={"name": name, "email": email, "message": message})
                response.raise_for_status()
                st.success("Form submitted successfully!")
            except requests.RequestException as e:
                st.error(f"Error submitting form: {e}")