import { useEffect, useState } from 'react';
import { get, post } from '../api';
import PageLayout from '../components/PageLayout';

export default function ElectricalNetwork() {
  const [loading, setLoading] = useState(true);
  const [msg, setMsg] = useState('');
  const [error, setError] = useState('');

  const [monitor, setMonitor] = useState({ voltage: '', current: '', quality: '' });
  const [alerts, setAlerts] = useState(false);
  const [security, setSecurity] = useState({ earthFault: false, rcm: false });
  const [loadBalancing, setLoadBalancing] = useState({ enabled: false, currentLimit: 32 });
  const [solar, setSolar] = useState({ capacity: 0, useSolar: false, handleExcess: false });

  useEffect(() => {
    const load = async () => {
      try {
        const cfg = await get('/api/v1/config/electrical');
        if (cfg.monitor) setMonitor(cfg.monitor);
        if (cfg.alerts !== undefined) setAlerts(cfg.alerts);
        if (cfg.security) setSecurity(cfg.security);
        if (cfg.loadBalancing) setLoadBalancing(cfg.loadBalancing);
        if (cfg.solar) setSolar(cfg.solar);
      } catch {
        // endpoint opcional
      } finally {
        setLoading(false);
      }
    };
    load();
  }, []);

  const save = async () => {
    setMsg('');
    setError('');
    try {
      const body = { monitor, alerts, security, loadBalancing, solar };
      await post('/api/v1/config/electrical', body);
      setMsg('Configuração gravada com sucesso!');
    } catch {
      setError('Erro ao gravar configuração.');
    }
  };

  return (
    <PageLayout title="Rede Elétrica">
      {msg && <div className="message success">{msg}</div>}
      {error && <div className="message error">{error}</div>}

      {loading ? (
        <p>A carregar...</p>
      ) : (
        <form className="form" onSubmit={e => { e.preventDefault(); save(); }}>
          <h2>Monitoramento da Rede Elétrica</h2>
          <div className="form-group">
            <label>Tensão de Entrada (V):</label>
            <input
              type="number"
              value={monitor.voltage}
              onChange={e => setMonitor({ ...monitor, voltage: e.target.value })}
            />
          </div>
          <div className="form-group">
            <label>Corrente de Entrada (A):</label>
            <input
              type="number"
              value={monitor.current}
              onChange={e => setMonitor({ ...monitor, current: e.target.value })}
            />
          </div>
          <div className="form-group">
            <label>Qualidade de Energia:</label>
            <input
              type="text"
              value={monitor.quality}
              onChange={e => setMonitor({ ...monitor, quality: e.target.value })}
            />
          </div>
          <div className="form-group">
            <label>
              <input
                type="checkbox"
                checked={alerts}
                onChange={e => setAlerts(e.target.checked)}
              />
              Alertas de Falha na Rede
            </label>
          </div>

          <h2>Proteção de Segurança Elétrica</h2>
          <div className="form-group">
            <label>
              <input
                type="checkbox"
                checked={security.earthFault}
                onChange={e => setSecurity({ ...security, earthFault: e.target.checked })}
              />
              Detecção de Falha de Aterramento
            </label>
          </div>
          <div className="form-group">
            <label>
              <input
                type="checkbox"
                checked={security.rcm}
                onChange={e => setSecurity({ ...security, rcm: e.target.checked })}
              />
              Proteção RCM
            </label>
          </div>

          <h2>Balanceamento de Carga</h2>
          <div className="form-group">
            <label>
              <input
                type="checkbox"
                checked={loadBalancing.enabled}
                onChange={e => setLoadBalancing({ ...loadBalancing, enabled: e.target.checked })}
              />
              Habilitar Balanceamento de Carga
            </label>
          </div>
          <div className="form-group">
            <label htmlFor="lb-current">Limite de Corrente (A):</label>
            <input
              id="lb-current"
              type="number"
              value={loadBalancing.currentLimit}
              onChange={e => setLoadBalancing({ ...loadBalancing, currentLimit: e.target.value })}
            />
          </div>

          <h2>Energia Solar</h2>
          <div className="form-group">
            <label htmlFor="solar-capacity">Capacidade Solar (kW):</label>
            <input
              id="solar-capacity"
              type="number"
              value={solar.capacity}
              onChange={e => setSolar({ ...solar, capacity: e.target.value })}
            />
          </div>
          <div className="form-group">
            <label>
              <input
                type="checkbox"
                checked={solar.useSolar}
                onChange={e => setSolar({ ...solar, useSolar: e.target.checked })}
              />
              Direcionar Energia Solar para o EVSE
            </label>
          </div>
          <div className="form-group">
            <label>
              <input
                type="checkbox"
                checked={solar.handleExcess}
                onChange={e => setSolar({ ...solar, handleExcess: e.target.checked })}
              />
              Gerenciamento de Excesso de Energia Solar
            </label>
          </div>

          <div className="button-grid">
            <button type="submit">Guardar</button>
          </div>
        </form>
      )}
    </PageLayout>
  );
}

