// src/pages/Connectivity.jsx
import React, { useState, useEffect } from 'react';
import { get, post } from '../api';
import PageLayout from '../components/PageLayout';

const Connectivity = () => {
  const [status, setStatus] = useState(null);
  const [loading, setLoading] = useState(true);

  const [wifiConfig, setWifiConfig] = useState({ ssid: '', password: '' });
  const [wifiNetworks, setWifiNetworks] = useState([]);
  const [wifiMsg, setWifiMsg] = useState('');

  const [mqttConfig, setMqttConfig] = useState({
    enabled: false,
    host: '',
    port: 1883,
    username: '',
    password: '',
    topic: '',
  });
  const [mqttMsg, setMqttMsg] = useState('');

  useEffect(() => {
    const load = async () => {
      try {
        const conn = await get('/api/v1/connectivity');
        setStatus(conn);
      } catch {
        // ignore errors in demo
      }
      try {
        const wifi = await get('/api/v1/config/wifi');
        setWifiConfig(wifi);
      } catch {}
      try {
        const list = await get('/api/v1/config/wifi/scan');
        setWifiNetworks(list.networks || []);
      } catch {}
      try {
        const mqtt = await get('/api/v1/config/mqtt');
        setMqttConfig(mqtt);
      } catch {}
      setLoading(false);
    };
    load();
  }, []);

  const saveWifi = async () => {
    try {
      await post('/api/v1/config/wifi', wifiConfig);
      setWifiMsg('Configuração Wi-Fi gravada!');
    } catch {
      setWifiMsg('Erro ao gravar Wi-Fi.');
    }
  };

  const saveMqtt = async () => {
    try {
      await post('/api/v1/config/mqtt', mqttConfig);
      setMqttMsg('Configuração MQTT gravada!');
    } catch {
      setMqttMsg('Erro ao gravar MQTT.');
    }
  };

  return (
    <PageLayout title="Conectividade">
      {loading ? (
        <p>A carregar...</p>
      ) : (
        <>
          {status && (
            <div>
              <h2>Status Atual</h2>
              <p>Wi-Fi: {status.wifi.status} ({status.wifi.ssid})</p>
              <p>MQTT: {status.mqtt.status} - {status.mqtt.broker}:{status.mqtt.port}</p>
            </div>
          )}

          <h2>Configuração Wi-Fi</h2>
          {wifiMsg && <div className="message">{wifiMsg}</div>}
          <form className="form" onSubmit={e => { e.preventDefault(); saveWifi(); }}>
            <div className="form-group">
              <label htmlFor="wifi-ssid">SSID:</label>
              <select
                id="wifi-ssid"
                value={wifiConfig.ssid}
                onChange={e => setWifiConfig({ ...wifiConfig, ssid: e.target.value })}
              >
                <option value="">-- Escolher --</option>
                {wifiNetworks.map(n => (
                  <option key={n.ssid} value={n.ssid}>{n.ssid}</option>
                ))}
              </select>
            </div>

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

            <div className="button-grid">
              <button type="submit">Guardar</button>
            </div>
          </form>

          <h2>Configuração MQTT</h2>
          {mqttMsg && <div className="message">{mqttMsg}</div>}
          <form className="form" onSubmit={e => { e.preventDefault(); saveMqtt(); }}>
            <div className="form-group">
              <label>
                <input
                  type="checkbox"
                  checked={mqttConfig.enabled}
                  onChange={e => setMqttConfig({ ...mqttConfig, enabled: e.target.checked })}
                />
                Ativar MQTT
              </label>
            </div>

            <div className="form-group">
              <label htmlFor="mqtt-host">Host:</label>
              <input
                id="mqtt-host"
                type="text"
                value={mqttConfig.host}
                onChange={e => setMqttConfig({ ...mqttConfig, host: e.target.value })}
              />
            </div>

            <div className="form-group">
              <label htmlFor="mqtt-port">Porta:</label>
              <input
                id="mqtt-port"
                type="number"
                value={mqttConfig.port}
                onChange={e => setMqttConfig({ ...mqttConfig, port: parseInt(e.target.value || 0) })}
              />
            </div>

            <div className="form-group">
              <label htmlFor="mqtt-username">Utilizador:</label>
              <input
                id="mqtt-username"
                type="text"
                value={mqttConfig.username}
                onChange={e => setMqttConfig({ ...mqttConfig, username: e.target.value })}
              />
            </div>

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

            <div className="form-group">
              <label htmlFor="mqtt-topic">Tópico:</label>
              <input
                id="mqtt-topic"
                type="text"
                value={mqttConfig.topic}
                onChange={e => setMqttConfig({ ...mqttConfig, topic: e.target.value })}
              />
            </div>

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

export default Connectivity;
