import React, { useRef, useEffect, useState } from 'react'; import { Line } from 'react-chartjs-2'; import ChartJS from 'chart.js/auto'; import zoomPlugin from 'chartjs-plugin-zoom'; import { getISOWeek, startOfDay, endOfDay, startOfWeek, endOfWeek, startOfMonth, endOfMonth, startOfYear, endOfYear, } from 'date-fns'; import { fetchPowerTimeseries, fetchForecast } from '@/app/utils/api'; import { color } from 'html2canvas/dist/types/css/types/color'; import DatePicker from 'react-datepicker'; import 'react-datepicker/dist/react-datepicker.css'; import './datepicker-dark.css'; // custom dark mode styles ChartJS.register(zoomPlugin); interface TimeSeriesEntry { time: string; value: number; } interface EnergyLineChartProps { siteId: string; } function groupTimeSeries( data: TimeSeriesEntry[], mode: 'day' | 'daily' | 'weekly' | 'monthly' | 'yearly' ): TimeSeriesEntry[] { const groupMap = new Map(); for (const entry of data) { const date = new Date(entry.time); let key = ''; switch (mode) { case 'day': const local = new Date(date.toLocaleString('en-US', { timeZone: 'Asia/Kuala_Lumpur' })); const hour = local.getHours(); const minute = local.getMinutes() < 30 ? '00' : '30'; const adjusted = new Date(local.setMinutes(minute === '00' ? 0 : 30, 0)); // zero seconds key = adjusted.toISOString(); // ✅ full timestamp key break; case 'daily': key = date.toLocaleDateString('en-MY', { timeZone: 'Asia/Kuala_Lumpur', weekday: 'short', day: '2-digit', month: 'short', }); break; case 'weekly': key = `${date.getFullYear()}-W${String(getISOWeek(date)).padStart(2, '0')}`; break; case 'monthly': key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`; break; case 'yearly': key = date.getFullYear().toString(); break; } if (!groupMap.has(key)) groupMap.set(key, []); groupMap.get(key)!.push(entry.value); } return Array.from(groupMap.entries()).map(([time, values]) => ({ time, value: values.reduce((sum, v) => sum + v, 0), })); } const EnergyLineChart = ({ siteId }: EnergyLineChartProps) => { const chartRef = useRef(null); const [viewMode, setViewMode] = useState<'day' | 'daily' | 'weekly' | 'monthly' | 'yearly'>('day'); const [consumption, setConsumption] = useState([]); const [generation, setGeneration] = useState([]); const [selectedDate, setSelectedDate] = useState(new Date()); const [forecast, setForecast] = useState([]); function useIsDarkMode() { const [isDark, setIsDark] = useState(() => typeof document !== 'undefined' ? document.body.classList.contains('dark') : false ); useEffect(() => { const check = () => setIsDark(document.body.classList.contains('dark')); const observer = new MutationObserver(check); observer.observe(document.body, { attributes: true, attributeFilter: ['class'] }); return () => observer.disconnect(); }, []); return isDark; } useEffect(() => { const now = new Date(); let start: Date; let end: Date; switch (viewMode) { case 'day': start = startOfDay(selectedDate); end = endOfDay(selectedDate); break; case 'daily': start = startOfWeek(now, { weekStartsOn: 1 }); end = endOfWeek(now, { weekStartsOn: 1 }); break; case 'weekly': start = startOfMonth(now); end = endOfMonth(now); break; case 'monthly': start = startOfYear(now); end = endOfYear(now); break; case 'yearly': start = new Date('2020-01-01'); end = now; break; } const isoStart = start.toISOString(); const isoEnd = end.toISOString(); const fetchData = async () => { try { const res = await fetchPowerTimeseries(siteId, isoStart, isoEnd); setConsumption(res.consumption); setGeneration(res.generation); // ⬇️ ADD THIS here — fetch forecast const forecastData = await fetchForecast(3.15, 101.7, 37, 0, 20.67); const selectedDateStr = selectedDate.toISOString().split('T')[0]; setForecast( forecastData .filter(({ time }) => time.startsWith(selectedDateStr)) // ✅ filter only selected date .map(({ time, forecast }) => ({ time, value: forecast })) ); } catch (error) { console.error('Failed to fetch energy timeseries:', error); } }; fetchData(); }, [siteId, viewMode, selectedDate]); const groupedConsumption = groupTimeSeries(consumption, viewMode); const groupedGeneration = groupTimeSeries(generation, viewMode); const groupedForecast = groupTimeSeries(forecast, viewMode); const forecastMap = Object.fromEntries(groupedForecast.map(d => [d.time, d.value])); const allTimes = Array.from(new Set([ ...groupedConsumption.map(d => d.time), ...groupedGeneration.map(d => d.time), ...groupedForecast.map(d => d.time), ])).sort((a, b) => new Date(a).getTime() - new Date(b).getTime()); const consumptionMap = Object.fromEntries(groupedConsumption.map(d => [d.time, d.value])); const generationMap = Object.fromEntries(groupedGeneration.map(d => [d.time, d.value])); const [startIndex, setStartIndex] = useState(0); const [endIndex, setEndIndex] = useState(allTimes.length - 1); useEffect(() => { if (typeof window !== 'undefined') { import('hammerjs'); } }, []); useEffect(() => { setStartIndex(0); setEndIndex(allTimes.length - 1); }, [viewMode, allTimes.length]); const formatLabel = (key: string) => { switch (viewMode) { case 'day': return new Date(key).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'Asia/Kuala_Lumpur', }); case 'monthly': return new Date(`${key}-01`).toLocaleString('en-GB', { month: 'short', year: 'numeric' }); case 'weekly': return key.replace('-', ' '); default: return key; } }; const filteredLabels = allTimes.slice(startIndex, endIndex + 1); const filteredConsumption = filteredLabels.map(t => consumptionMap[t] ?? 0); const filteredGeneration = filteredLabels.map(t => generationMap[t] ?? 0); const filteredForecast = filteredLabels.map(t => forecastMap[t] ?? null); const allValues = [...filteredConsumption, ...filteredGeneration].filter(v => v !== null) as number[]; const maxValue = allValues.length > 0 ? Math.max(...allValues) : 0; const yAxisSuggestedMax = maxValue * 1.15; const isDark = useIsDarkMode(); const axisColor = isDark ? '#fff' : '#222'; function areaGradient(ctx: any, hex: string, alphaTop = 0.22, alphaBottom = 0.02) { const { ctx: g, chartArea } = ctx.chart; if (!chartArea) return hex; // initial render fallback const gradient = g.createLinearGradient(0, chartArea.top, 0, chartArea.bottom); // top more opaque → bottom fades out gradient.addColorStop(0, hex + Math.floor(alphaTop * 255).toString(16).padStart(2, '0')); gradient.addColorStop(1, hex + Math.floor(alphaBottom * 255).toString(16).padStart(2, '0')); return gradient; } // Define colors for both light and dark modes const consumptionColor = isDark ? '#B80F0A' : '#EF4444'; // Example: Brighter red for dark mode const generationColor = isDark ? '#48A860' : '#22C55E'; // Example: Brighter green for dark mode const forecastColor = '#fcd913'; // A golden yellow that works well in both modes const data = { labels: filteredLabels.map(formatLabel), datasets: [ { label: 'Consumption', data: filteredConsumption, borderColor: consumptionColor, backgroundColor: (ctx: any) => areaGradient(ctx, consumptionColor), fill: true, // <-- fill under line tension: 0.4, spanGaps: true, }, { label: 'Generation', data: filteredGeneration, borderColor: generationColor, backgroundColor: (ctx: any) => areaGradient(ctx, generationColor), fill: true, // <-- fill under line tension: 0.4, spanGaps: true, }, { label: 'Forecasted Solar', data: filteredForecast, borderColor: '#fcd913', // orange backgroundColor: (ctx: any) => areaGradient(ctx, '#fcd913', 0.18, 0.03), tension: 0.4, borderDash: [5, 5], // dashed line to distinguish forecast fill: true, spanGaps: true, } ], }; const options = { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'top', labels: { color: axisColor, // legend text color }, }, zoom: { zoom: { wheel: { enabled: true }, pinch: { enabled: true }, mode: 'x' as const, }, pan: { enabled: true, mode: 'x' as const }, }, tooltip: { enabled: true, mode: 'index', intersect: false, backgroundColor: isDark ? '#232b3e' : '#fff', titleColor: axisColor, bodyColor: axisColor, borderColor: isDark ? '#444' : '#ccc', borderWidth: 1, }, }, scales: { x: { title: { display: true, color: axisColor, text: viewMode === 'day' ? 'Time (HH:MM)' : viewMode === 'daily' ? 'Day' : viewMode === 'weekly' ? 'Week' : viewMode === 'monthly' ? 'Month' : 'Year', font: { weight: 'normal' as const }, }, ticks: { color: axisColor, }, }, y: { beginAtZero: true, suggestedMax: yAxisSuggestedMax, title: { display: true, text: 'Power (kW)', color: axisColor, font: { weight: 'normal' as const }, }, ticks: { color: axisColor, }, }, }, } as const; const handleResetZoom = () => { chartRef.current?.resetZoom(); }; return (

Energy Consumption & Generation

{viewMode === 'day' && ( )}
); }; export default EnergyLineChart;