import { useState, useEffect } from 'react'; import { useParams, useNavigate } from 'react-router-dom'; import { Play, Square, Zap, BatteryCharging, Clock, Activity, Loader2, ArrowLeft, } from 'lucide-react'; import { motion, AnimatePresence } from 'framer-motion'; import { SectionCard } from '@/components/ui/SectionCard'; import { getAuthHeader } from '@/utils/apiAuthHeader'; import { useToast } from '@/components/ToastContext'; export default function ChargerDashboard() { const { chargerId } = useParams(); // Obter o chargerId da URL const [dados, setDados] = useState(null); const [ampLimit, setAmpLimit] = useState(6); const [maxAmps, setMaxAmps] = useState(32); const [error, setError] = useState(''); const [loading, setLoading] = useState(true); const [busy, setBusy] = useState(false); const navigate = useNavigate(); const showToast = useToast(); // Buscar status do carregador useEffect(() => { if (!chargerId) { setError("Carregador não encontrado!"); setLoading(false); return; } let cancelado = false; async function fetchStatus() { setLoading(true); setError(''); try { const res = await fetch(`/api/chargers/${chargerId}/status`, { headers: getAuthHeader(), }); const json = await res.json(); if (!res.ok || !json.success) throw new Error(json.message || 'Erro ao obter status'); if (!cancelado) { setDados(json.data); setAmpLimit(json.data.ampLimit ?? 6); setMaxAmps(json.data.maxAmps ?? 32); } } catch (err) { if (!cancelado) setError(err.message || 'Falha ao buscar status'); } finally { if (!cancelado) setLoading(false); } } fetchStatus(); const interval = setInterval(fetchStatus, 8000); return () => { cancelado = true; clearInterval(interval); }; }, [chargerId]); // Atualizar a requisição sempre que o chargerId mudar // Enviar comandos (iniciar/parar carregamento) async function handleAction(action) { if (!chargerId) return; // Adicionar verificação extra para chargerId setBusy(true); try { const res = await fetch(`/api/chargers/${chargerId}/${action}`, { method: 'POST', headers: { ...getAuthHeader(), 'Content-Type': 'application/json', }, body: JSON.stringify({ ampLimit }), }); const json = await res.json(); if (!res.ok || !json.success) throw new Error(json.message || 'Erro ao enviar comando'); setDados(json.data); showToast( action === 'start' ? 'Carregamento iniciado' : 'Carregamento parado', 'success' ); setError(''); } catch (err) { setError(err.message); showToast(err.message, 'error'); } finally { setBusy(false); } } return (