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

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('Alterações guardadas com sucesso!');
    } catch {
      setMsg('Erro ao guardar alterações.');
    }
  };

  return (
    <PageLayout title="Configuração Wi-Fi">
      {msg && <Alert type={msg.startsWith('Erro') ? 'error' : 'success'}>{msg}</Alert>}

      {loading ? (
        <p>A carregar...</p>
      ) : (
        <form className="flex flex-col gap-4" onSubmit={(e) => { e.preventDefault(); save(); }}>
          <div>
            <label className="block mb-1" htmlFor="ssid">SSID:</label>
            <select
              id="ssid"
              className="border border-gray-300 rounded px-3 py-2 w-full"
              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>
            <label className="block mb-1" htmlFor="password">Palavra-passe:</label>
            <input
              id="password"
              type="password"
              className="border border-gray-300 rounded px-3 py-2 w-full"
              value={config.password}
              onChange={e => setConfig({ ...config, password: e.target.value })}
            />
          </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>
  );
}
