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="p-2 mb-2 bg-green-600 text-white rounded">{msg}</div>}
      {error && <div className="p-2 mb-2 bg-red-600 text-white rounded">{error}</div>}

      {loading ? (
        <p>A carregar...</p>
      ) : (
        <form className="flex flex-col gap-4" onSubmit={e => { e.preventDefault(); save(); }}>
          <h2 className="text-xl font-semibold">Monitoramento da Rede Elétrica</h2>
          <div>
            <label className="block mb-1">Tensão de Entrada (V):</label>
            <input
              type="number"
              className="border border-gray-300 rounded px-3 py-2 w-full"
              value={monitor.voltage}
              onChange={e => setMonitor({ ...monitor, voltage: e.target.value })}
            />
          </div>
          <div>
            <label className="block mb-1">Corrente de Entrada (A):</label>
            <input
              type="number"
              className="border border-gray-300 rounded px-3 py-2 w-full"
              value={monitor.current}
              onChange={e => setMonitor({ ...monitor, current: e.target.value })}
            />
          </div>
          <div>
            <label className="block mb-1">Qualidade de Energia:</label>
            <input
              type="text"
              className="border border-gray-300 rounded px-3 py-2 w-full"
              value={monitor.quality}
              onChange={e => setMonitor({ ...monitor, quality: e.target.value })}
            />
          </div>
          <div>
            <label className="flex items-center gap-2">
              Alertas de Falha na Rede
              <input
                type="checkbox"
                checked={alerts}
                onChange={e => setAlerts(e.target.checked)}
              />
            </label>
          </div>

          <h2 className="text-xl font-semibold">Proteção de Segurança Elétrica</h2>
          <div>
            <label className="flex items-center gap-2">
              Detecção de Falha de Aterramento
              <input
                type="checkbox"
                checked={security.earthFault}
                onChange={e => setSecurity({ ...security, earthFault: e.target.checked })}
              />
            </label>
          </div>
          <div>
            <label className="flex items-center gap-2">
              Proteção RCM
              <input
                type="checkbox"
                checked={security.rcm}
                onChange={e => setSecurity({ ...security, rcm: e.target.checked })}
              />
            </label>
          </div>

          <h2 className="text-xl font-semibold">Balanceamento de Carga</h2>
          <div>
            <label className="flex items-center gap-2">
              Habilitar Balanceamento de Carga
              <input
                type="checkbox"
                checked={loadBalancing.enabled}
                onChange={e => setLoadBalancing({ ...loadBalancing, enabled: e.target.checked })}
              />
            </label>
          </div>
          <div>
            <label className="block mb-1" htmlFor="lb-current">Limite de Corrente (A):</label>
            <input
              id="lb-current"
              type="number"
              className="border border-gray-300 rounded px-3 py-2 w-full"
              value={loadBalancing.currentLimit}
              onChange={e => setLoadBalancing({ ...loadBalancing, currentLimit: e.target.value })}
            />
          </div>

          <h2 className="text-xl font-semibold">Energia Solar</h2>
          <div>
            <label className="block mb-1" htmlFor="solar-capacity">Capacidade Solar (kW):</label>
            <input
              id="solar-capacity"
              type="number"
              className="border border-gray-300 rounded px-3 py-2 w-full"
              value={solar.capacity}
              onChange={e => setSolar({ ...solar, capacity: e.target.value })}
            />
          </div>
          <div>
            <label className="flex items-center gap-2">
              Direcionar Energia Solar para o EVSE
              <input
                type="checkbox"
                checked={solar.useSolar}
                onChange={e => setSolar({ ...solar, useSolar: e.target.checked })}
              />
            </label>
          </div>
          <div>
            <label className="flex items-center gap-2">
              Gerenciamento de Excesso de Energia Solar
              <input
                type="checkbox"
                checked={solar.handleExcess}
                onChange={e => setSolar({ ...solar, handleExcess: e.target.checked })}
              />
            </label>
          </div>
          <div>
            <button className="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700" type="submit">Guardar</button>
          </div>
        </form>
      )}
    </PageLayout>
  );
}

