import React, { useMemo, useState, useEffect } from 'react'; import { XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, Area, AreaChart, ReferenceLine, } from 'recharts'; import { EnvironmentData } from '../types.ts'; import { Thermometer, Droplets, Wind, Clock, ChevronDown } from 'lucide-react'; interface EnvironmentChartProps { data: EnvironmentData[]; } type TimeRange = '1h' | '6h' | '12h' | '24h' | '3d' | '7d'; interface TimeRangeOption { value: TimeRange; label: string; hours: number; } const TIME_RANGE_OPTIONS: TimeRangeOption[] = [ { value: '1h', label: '1 Jam Terakhir', hours: 1 }, { value: '6h', label: '6 Jam Terakhir', hours: 6 }, { value: '12h', label: '12 Jam Terakhir', hours: 12 }, { value: '24h', label: '24 Jam Terakhir', hours: 24 }, { value: '3d', label: '3 Hari Terakhir', hours: 72 }, { value: '7d', label: '1 Minggu Terakhir', hours: 168 }, ]; const EnvironmentChart: React.FC = ({ data }) => { // Live WIB timestamp that updates every second const [currentWibTime, setCurrentWibTime] = useState(''); const [timeRange, setTimeRange] = useState('12h'); const [isDropdownOpen, setIsDropdownOpen] = useState(false); useEffect(() => { const updateTime = () => { const wibTime = new Date().toLocaleString('id-ID', { timeZone: 'Asia/Jakarta', hour: '2-digit', minute: '2-digit', second: '2-digit', day: '2-digit', month: 'short', year: 'numeric', }); setCurrentWibTime(wibTime); }; // Update immediately updateTime(); // Update every second const interval = setInterval(updateTime, 1000); return () => clearInterval(interval); }, []); // Filter data based on selected time range const filteredData = useMemo(() => { if (!data || data.length === 0) return []; const selectedRange = TIME_RANGE_OPTIONS.find((opt) => opt.value === timeRange); if (!selectedRange) return data; const hoursToShow = selectedRange.hours; const now = new Date(); const cutoffTime = new Date(now.getTime() - hoursToShow * 60 * 60 * 1000); // Filter data within the time range return data.filter((item) => { // Parse the time string (format: "HH:MM" or "DD MMM HH:MM") // This is a simple implementation - adjust based on your actual time format const itemTime = new Date(item.time); return itemTime >= cutoffTime; }); }, [data, timeRange]); // Calculate current values (latest reading from filtered data) const currentValues = useMemo(() => { if (!filteredData || filteredData.length === 0) return null; const latest = filteredData[filteredData.length - 1]; if (!latest) return null; return { suhu: latest.Suhu, kelembapan: latest.Kelembapan, amonia: latest.Amonia, time: latest.time, }; }, [filteredData]); // Calculate status for each metric const getTemperatureStatus = (temp: number) => { if (temp < 28 || temp > 34) return 'critical'; if (temp < 30 || temp > 32) return 'warning'; return 'ok'; }; const getHumidityStatus = (humidity: number) => { if (humidity < 50 || humidity > 70) return 'warning'; if (humidity < 40 || humidity > 80) return 'critical'; return 'ok'; }; const getAmmoniaStatus = (ammonia: number) => { if (ammonia > 25) return 'critical'; if (ammonia > 15) return 'warning'; return 'ok'; }; // Get evenly spaced ticks (show every 2 hours or available data) const getTicks = () => { if (!filteredData || filteredData.length === 0) return []; // Get all hourly marks const hourlyData = filteredData.filter((item) => item.time.endsWith(':00')); // If we have hourly data, show every 2 hours to avoid crowding if (hourlyData.length > 6) { return hourlyData.filter((_item, index) => index % 2 === 0).map((item) => item.time); } // Otherwise show all hourly marks if (hourlyData.length > 0) { return hourlyData.map((item) => item.time); } // If no hourly marks, show evenly spaced data points const step = Math.ceil(filteredData.length / 6); return filteredData.filter((_item, index) => index % step === 0).map((item) => item.time); }; // Custom tooltip const CustomTooltip = ({ active, payload }: any) => { if (active && payload && payload.length) { return (

{payload[0].payload.time}

{payload.map((entry: any, index: number) => (
{entry.name}: {typeof entry.value === 'number' ? entry.value.toFixed(1) : entry.value}
))}
); } return null; }; const hasNoData = !filteredData || filteredData.length === 0; const selectedRangeOption = TIME_RANGE_OPTIONS.find((opt) => opt.value === timeRange); const handleTimeRangeChange = (value: TimeRange) => { setTimeRange(value); setIsDropdownOpen(false); }; return (
{/* Header */}

Monitoring Lingkungan

{selectedRangeOption?.label} {currentValues && ( • Update terakhir: {currentValues.time} )}

{/* Time Range Dropdown */}
{isDropdownOpen && ( <> {/* Backdrop */}
setIsDropdownOpen(false)} >
{/* Dropdown Menu */}
{TIME_RANGE_OPTIONS.map((option) => ( ))}
)}
{currentValues && (
Live
)} {currentWibTime && (
WIB: {currentWibTime}
)}
{/* Current Values Summary */} {currentValues && (
{/* Temperature */}

Suhu

{currentValues.suhu.toFixed(1)}°C

{/* Humidity */}

Kelembapan

{currentValues.kelembapan.toFixed(1)}%

{/* Ammonia */}

Amonia

{currentValues.amonia.toFixed(1)} ppm

)} {/* Chart */}
{hasNoData ? (

Tidak ada data tersedia

Tidak ada data IoT dalam rentang waktu ini

) : ( } /> {/* Optimal range indicators */} )}
); }; export default EnvironmentChart;