import streamlit as st
import pandas as pd

# Import KPI function & fallback loader
from utils.kpi import compute_kpis
from utils.data_loaders import load_all

# Import the new API client (same level as dashboard.py)
from api_client import WarehouseAPI


def _low_stock_table(inventory: pd.DataFrame, default_threshold: int = 100) -> pd.DataFrame:
    """Generate a low stock alert table with safe fallbacks."""
    if inventory is None or inventory.empty:
        return pd.DataFrame()

    # Normalize on_hand column
    if "on_hand" not in inventory.columns:
        for alt in ("qty_on_hand", "quantity", "stock"):
            if alt in inventory.columns:
                inventory = inventory.rename(columns={alt: "on_hand"})
                break
        else:
            inventory["on_hand"] = 0

    # Determine condition logic
    if "reorder_point" in inventory.columns:
        cond = inventory["on_hand"] <= inventory["reorder_point"]
    else:
        cond = inventory["on_hand"] <= default_threshold

    alerts = inventory.loc[cond].copy()

    if not alerts.empty:
        sort_cols = [c for c in ["on_hand", "sku", "warehouse_id"] if c in alerts.columns]
        alerts = alerts.sort_values(sort_cols)

    return alerts


def show() -> None:
    st.subheader("Manager View: Global KPIs & Low-Stock Alerts")

    api = WarehouseAPI()   # Create API client instance

    # Try API first
    try:
        inv = api.get_inventory()
        skus = api.get_products()    # uses get_products() since "skus" no longer exists
        orders = api.get_orders()
        api_ok = True
    except Exception as e:
        st.warning(f"API unavailable, falling back to CSVs. Error: {e}")
        api_ok = False
        inv = skus = orders = None

    # CSV fallback logic
    if not api_ok or any(x is None for x in (inv, skus, orders)):
        data = load_all()
        inv = inv if inv is not None else data["inventory"]
        skus = skus if skus is not None else data["skus"]
        orders = orders if orders is not None else data["orders"]

    # ---- KPI CALCULATION ----
    # Old signature: compute_kpis(orders, order_status, inv, skus)
    # New simplified: compute_kpis(orders, inv, skus)

    kpis = compute_kpis(orders, inv, skus)

    # ---- KPI DISPLAY ----
    c1, c2, c3, c4 = st.columns(4)
    c1.metric("On-time delivery %", f"{kpis.get('on_time_pct', '—')}%")

    inv_val = kpis.get("inventory_value", None)
    c2.metric("Inventory value", f"${inv_val:,}" if isinstance(inv_val, (int, float)) else "—")

    c3.metric("Backorders", kpis.get("backorders", "—"))
    c4.metric("Return rate %", f"{kpis.get('return_rate', '—')}%")

    # ---- LOW STOCK ALERTS ----
    st.markdown("### 🔻 Low-stock alerts")
    alerts = _low_stock_table(inv)

    df_display = alerts.rename(columns={
    "product_id": "Product ID",
    "warehouse_id": "Warehouse",
    "q_on_hand": "On Hand",
    "q_reserved": "Reserved",
    "last_update": "Last Updated",
    "condition": "Condition",
    "sku": "SKU",
    "q_in_transit": "In Transit",
    "reorder_point": "Reorder Point",
    "location": "Location",
    "safety_stock": "Safety Stock",
    "inventory_id": "Inventory ID"
})
    if alerts.empty:
        
        st.dataframe(df_display, use_container_width=True)
    else:
        # st.success("No low-stock items right now ✅")
        st.dataframe(df_display, use_container_width=True)
        


# REQUIRED BY STREAMLIT PAGE ENGINE
show()
