import streamlit as st
import pandas as pd
import datetime
import os
import plotly.io as pio
from eda_ts.helper_functions import format_value, is_invalid_path
from eda_ts.constants import PKL_PATH_KEY, DF_KEY, SEC_TO_DAY, SEC_TO_HOUR
import plotly.express as px

pio.templates.default = "plotly"

st.set_page_config(
    page_title="Overview",
    page_icon="🏠",
    layout="wide"
)
st.title("🏠 Overview")

def path_info(pkl_path):
    return {
        "File Path": pkl_path,
        "File Size": f"{os.path.getsize(pkl_path) / (1024 * 1024) :.2f} MB",
        "Creation Time": datetime.datetime.fromtimestamp(os.path.getctime(pkl_path)).strftime('%Y-%m-%d %H:%M:%S'),
        "Modification Time":  datetime.datetime.fromtimestamp(os.path.getmtime(pkl_path)).strftime('%Y-%m-%d %H:%M:%S'),
        "Last Access Time": datetime.datetime.fromtimestamp(os.path.getatime(pkl_path)).strftime('%Y-%m-%d %H:%M:%S'),
    }

def index_info(df):
    return {
        'Size': len(df.index),
        'Type': str(type(df.index).__name__),
        'Start': format_value(df.index[0]),
        'End': format_value(df.index[-1]),
        'Timezone': format_value(df.index.tz),
        'Duration': f"{(df.index[-1] - df.index[0]).total_seconds() / 86400:.1f} days",
        'Monotonic Inc.': format_value(df.index.is_monotonic_increasing),
        'Frequency': format_value(df.index.freq) if df.index.freq else "Variable",
    }

def enhanced_describe(df):
    desc = df.describe()
    desc.loc['nan%'] = (df.isna().sum() / len(df) * 100).round(2)
    desc.loc['zero%'] = ((df == 0).sum() / len(df) * 100).round(2)

    return desc



        
pkl_path = st.text_input("Enter the path to your pickle file:")
submit_button = st.button("Submit")
if submit_button:
    if is_invalid_path(pkl_path):
        st.error(f"Invalid path '{pkl_path}'. Please enter a valid path.")
    else:
        st.session_state[DF_KEY] = pd.read_pickle(pkl_path)
        st.session_state[PKL_PATH_KEY] = pkl_path
        st.success("File successfully loaded!")


if st.session_state[PKL_PATH_KEY] is not None and st.session_state[DF_KEY] is not None:
    pkl_path = st.session_state[PKL_PATH_KEY]
    df = st.session_state[DF_KEY]

    st.write("#### Path Info")
    path_details = path_info(pkl_path)
    st.write(path_details)

    col1, col2 = st.columns([3, 1])  # 75% and 25% width
    with col1:
        st.write("#### Data Info")
        st.dataframe(enhanced_describe(df), use_container_width=True)
    with col2:
        st.write("#### Index Info")
        if isinstance(df.index, pd.DatetimeIndex):
            time_df = index_info(df)
            st.dataframe(time_df, use_container_width=True)
        else:
            st.write("⚠️ Index is not a DatetimeIndex")

    st.write("### Data Preview")
    col1, col2 = st.columns(2)

    with col1:
        head_size = st.number_input("Head size", min_value=1, max_value=len(df), value=5)
        st.write(f"#### Head (First {head_size} Rows)")
        st.dataframe(df.head(head_size), use_container_width=True)

    with col2:
        tail_size = st.number_input("Tail size", min_value=1, max_value=len(df), value=5)
        st.write(f"#### Tail (Last {tail_size} Rows)")
        st.dataframe(df.tail(tail_size), use_container_width=True)

    # plot df:
    st.write("### Data Plot")
    slice_size = 20_000 
    if len(df) > slice_size:
        freq_td = df.index.freq.delta
        total_seconds = freq_td.total_seconds() * slice_size
        days = total_seconds // SEC_TO_DAY
        hours = (total_seconds % SEC_TO_DAY) // SEC_TO_HOUR
        st.info(f"We slice dfs with more than {slice_size / 1000}k rows ({int(days)} days {int(hours)} hours), to prevent performance issues.")
        slices = [df[i: i+slice_size] for i in range(0, len(df), slice_size)]
        slice_index = st.selectbox(
            "Select a data slice", 
            list(range(len(slices))), 
            format_func=lambda x: f"Slice #{x+1}: from {slices[x].index[0].date()} to {slices[x].index[-1].date()}"
        )
        df_to_plot = slices[slice_index]
    else:
        df_to_plot = df
    st.plotly_chart(px.line(df_to_plot), use_container_width=True)



