import React, { useEffect, useState } from "react"; interface KPI_TableProps { siteId: string; month: string; // format: "YYYY-MM" } interface MonthlyKPI { site: string; month: string; yield_kwh: number | null; consumption_kwh: number | null; grid_draw_kwh: number | null; efficiency: number | null; peak_demand_kw: number | null; avg_power_factor: number | null; load_factor: number | null; } const KPI_Table: React.FC = ({ siteId, month }) => { const [kpiData, setKpiData] = useState(null); const [loading, setLoading] = useState(false); const API_URL = process.env.NEXT_PUBLIC_FASTAPI_URL; useEffect(() => { if (!siteId || !month) return; const fetchKPI = async () => { setLoading(true); try { const res = await fetch( `${API_URL}/kpi/monthly?site=${siteId}&month=${month}` ); setKpiData(await res.json()); } catch (err) { console.error("Failed to fetch KPI:", err); setKpiData(null); } finally { setLoading(false); } }; fetchKPI(); }, [siteId, month]); const formatValue = (value: number | null, unit = "", decimals = 2) => value != null ? `${value.toFixed(decimals)}${unit}` : "—"; const rows = [ { label: "Monthly Yield", value: formatValue(kpiData?.yield_kwh ?? null, " kWh", 0) }, { label: "Monthly Consumption", value: formatValue(kpiData?.consumption_kwh ?? null, " kWh", 0) }, { label: "Monthly Grid Draw", value: formatValue(kpiData?.grid_draw_kwh ?? null, " kWh", 0) }, { label: "Efficiency", value: formatValue(kpiData?.efficiency ?? null, "%", 1) }, { label: "Peak Demand", value: formatValue(kpiData?.peak_demand_kw ?? null, " kW") }, { label: "Power Factor", value: formatValue(kpiData?.avg_power_factor ?? null) }, { label: "Load Factor", value: formatValue(kpiData?.load_factor ?? null) }, ]; return (

Monthly KPI

{!siteId ? (

No site selected

) : loading ? (

Loading...

) : ( {rows.map((row) => ( ))}
KPI Value
{row.label} {row.value}
)}
); }; export default KPI_Table;