import streamlit as st
import altair as alt
import pandas as pd

inventory = st.session_state["inventory"]
warehouses = st.session_state["warehouses"]
product = st.session_state["product"]

st.title("Warehouse Overview")

warehouses_list = inventory["warehouse_id"].unique()
selected_wh = st.selectbox("Select Warehouse", sorted(warehouses_list))

if selected_wh:
    inventory_filtered = inventory[inventory["warehouse_id"] == selected_wh]
    
    rename_map = {
    "product_id": "Product ID",
    "warehouse_id": "Warehouse",
    "q_on_hand": "Quantity On Hand",
    "q_reserved": "Reserved",
    "last_update": "Last Updated",
    "condition": "Condition",
    "sku": "SKU",
    "q_in_transit": "Quantity In Transit",
    "reorder_point": "Reorder Point",
    "location": "Location",
    "safety_stock": "Safety Stock",
    "inventory_id": "Inventory ID"
}

    display_df = inventory_filtered.rename(columns=rename_map)
    #st.dataframe(display_df)



    st.subheader("Condition Breakdown")
    if "condition" in inventory_filtered.columns:
        condition_sums = inventory_filtered.groupby(["warehouse_id", "condition"])["q_on_hand"].sum().reset_index()
        chart = alt.Chart(condition_sums).mark_bar().encode(
            y=alt.Y("condition:N", title="Condition"), 
            x=alt.X("q_on_hand:Q", title="Quantity On Hand"), 
            color=alt.Color("condition:N", title="Condition")
        )
        #st.altair_chart(chart, width='stretch')
    #----------------------------------------------------
    #Loads Condition breakdown and Dataframes sideby side 
    #----------------------------------------------------
    col1, col2 = st.columns(2)
    with col1: 
        st.dataframe(display_df)
    with col2: 
        st.altair_chart(chart, width='stretch')

    
    st.subheader("Warehouse Map")
    if {"latitude", "longitude"}.issubset(warehouses.columns):
        map_data = warehouses.dropna(subset=["latitude", "longitude"])
        st.map(map_data)