import streamlit as st
from api_client import WarehouseAPI

def render_transfer_page():
    st.title("Inventory Transfer")

    api = WarehouseAPI()

    # Validate session state keys
    required_keys = ["product", "warehouses", "inventory"]
    if not all(key in st.session_state for key in required_keys):
        st.warning("Data not loaded yet. Visit the Dashboard first.")
        return

    # Load the data
    products_df = st.session_state["product"]
    warehouses_df = st.session_state["warehouses"]

    sku = st.selectbox("Select SKU", products_df["sku"].unique())
    from_wh = st.selectbox("From Warehouse", warehouses_df["warehouse_id"].unique())
    to_wh = st.selectbox("To Warehouse", warehouses_df["warehouse_id"].unique())
    qty = st.number_input("Quantity to Transfer", min_value=1, value=1)

    if st.button("Transfer"):
        try:
            response = api.transfer_inventory(sku, from_wh, to_wh, qty)

            # Safely extract message from API response
            msg = response.get("message", "Transfer completed successfully.")
            st.success(msg)

        except Exception as e:
            # If an error occurs, do not break the UI
            st.error(f"Transfer failed: {e}")

        finally:
            # ALWAYS show this notice
            st.info("Note: This is a demo. Changes are not saved to the database.")

# 👉 IMPORTANT: Call the function
render_transfer_page()
