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

export default function Wifi() {
  const [config, setConfig] = useState({ ssid: '', password: '' });
  const [networks, setNetworks] = useState([]);
  const [msg, setMsg] = useState('');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadConfig();
    scanNetworks();
  }, []);

  const loadConfig = async () => {
    try {
      const data = await get('/api/v1/config/wifi');
      setConfig(data);
    } catch {
      setMsg('Erro ao carregar configuração.');
    } finally {
      setLoading(false);
    }
  };

  const scanNetworks = async () => {
    try {
      const result = await get('/api/v1/config/wifi/scan');
      setNetworks(result.networks || []);
    } catch {
      setMsg('Erro ao procurar redes Wi-Fi.');
    }
  };

  const save = async () => {
    try {
      await post('/api/v1/config/wifi', config);
      setMsg('Configuração gravada com sucesso!');
    } catch {
      setMsg('Erro ao gravar.');
    }
  };

  return (
    <PageLayout title="Configuração Wi-Fi">
      {msg && <div className="message">{msg}</div>}

      {loading ? (
        <p>A carregar...</p>
      ) : (
        <form className="form" onSubmit={(e) => { e.preventDefault(); save(); }}>
          <div className="form-group">
            <label htmlFor="ssid">SSID:</label>
            <select
              id="ssid"
              value={config.ssid}
              onChange={e => setConfig({ ...config, ssid: e.target.value })}
            >
              <option value="">-- Escolher --</option>
              {networks.map(n => (
                <option key={n.ssid} value={n.ssid}>{n.ssid}</option>
              ))}
            </select>
          </div>

          <div className="form-group">
            <label htmlFor="password">Palavra-passe:</label>
            <input
              id="password"
              type="password"
              value={config.password}
              onChange={e => setConfig({ ...config, password: e.target.value })}
            />
          </div>

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