# dashboard.py
import streamlit as st
import matplotlib.pyplot as pl
import pandas as pd
import main
from main import (
    start_sim,
    stop_sim,
    reset_sim,
)
import time


st.set_page_config(layout="wide")

# Header
st.logo("https://rooftop.my/logo.svg", size="large")
st.title("MEOS Control Dashboard")
st.subheader("Mobile Energy Operations Simulation (MEOS)")
st.text("Run MEOS Simulation and Monitor MBESS Status")

# some instructions

# --- SESSION STATE SETUP ---
if "running" not in st.session_state:
    st.session_state.running = False
if "plot_area" not in st.session_state:
    st.session_state.plot_area = st.empty()

# --- CONTROL BUTTONS ---
col1, col2, col3 = st.columns(3)
with col1:
    if st.button("Start", use_container_width=True):
        start_sim()
        st.session_state.running = True
with col2:
    if st.button("Stop", use_container_width=True):
        stop_sim()
        st.session_state.running = False
with col3:
    if st.button("Reset", use_container_width=True):
        reset_sim()
        st.session_state.running = False

placeholder = st.empty()


def show_table():
    df = main.status_df
    if df is None or df.empty:
        placeholder.text("Waiting for first simulation step…")
    else:
        placeholder.dataframe(
            df,
            column_config={
                "Site Name": st.column_config.TextColumn("Site Name"),
                "MBESS Unit": st.column_config.TextColumn(
                    "MBESS Unit", help="Name of the MBESS unit at the site"
                ),
                "Current Load (kW)": st.column_config.NumberColumn(
                    "Current Load (kW)", help="Current BESS discharge load in kW"
                ),
                "SoC (%)": st.column_config.ProgressColumn(
                    "State of Charge",
                    help="State of Charge of the BESS unit",
                    format="%.1f%%",
                    min_value=0,
                    max_value=100,
                ),
                "Predicted Swap Time": st.column_config.TextColumn(
                    "Predicted Swap Time", help="Predicted time for BESS swap"
                ),
                "Cycle Discharge Profile": st.column_config.LineChartColumn(
                    "Cycle Discharge Profile",
                    help="Cycle discharge profile of the BESS unit",
                ),
                "Load Profile Since Start": st.column_config.LineChartColumn(
                    "Load Profile Since Start",
                    help="Load profile since the start of the simulation",
                ),
            },
            use_container_width=True,
        )


if st.session_state.running:
    # display simulation start time
    st.metric(
        "Simulation Start Time",
        value=pd.to_datetime(main.c["sim_start_time"], unit="s").strftime(
            "%Y-%m-%d %H:%M:%S"
        ),
    )
    st.metric(
        "Time Elapsed in DD:HH:MM:SS",
        value=str(pd.to_timedelta(main.sim_i * main.dt, unit="s")),
    )
    # display BESS data, SoC, Load Consumption
    show_table()
    time.sleep(3)
    st.rerun()
else:
    show_table()
    st.info("Simulation not running")
