// 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 className="text-xl font-semibold mt-4">Configuração Wi-Fi</h2>
          {wifiMsg && <div className="p-2 bg-gray-200 rounded mb-2">{wifiMsg}</div>}
          <form className="flex flex-col gap-4" onSubmit={e => { e.preventDefault(); saveWifi(); }}>

            <div>
              <label className="block mb-1" htmlFor="wifi-ssid">SSID:</label>
              <input
                id="wifi-ssid"
                type="text"
                className="border border-gray-300 rounded px-3 py-2 w-full"
                value={wifiConfig.ssid}
                onChange={e => setWifiConfig({ ...wifiConfig, ssid: e.target.value })}
              />
            </div>


            <div>
              <label className="block mb-1" htmlFor="wifi-password">Palavra-passe:</label>
              <input
                id="wifi-password"
                type="password"
                className="border border-gray-300 rounded px-3 py-2 w-full"
                value={wifiConfig.password}
                onChange={e => setWifiConfig({ ...wifiConfig, 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>

          <h2 className="text-xl font-semibold mt-6">Configuração MQTT</h2>
          {mqttMsg && <div className="p-2 bg-gray-200 rounded mb-2">{mqttMsg}</div>}
          <form className="flex flex-col gap-4" onSubmit={e => { e.preventDefault(); saveMqtt(); }}>
            <div>
              <label className="flex items-center gap-2">
                Ativar MQTT
                <input
                  type="checkbox"
                  checked={mqttConfig.enabled}
                  onChange={e => setMqttConfig({ ...mqttConfig, enabled: e.target.checked })}
                />
              </label>
            </div>

            <div>
              <label className="block mb-1" htmlFor="mqtt-host">Host:</label>
              <input
                id="mqtt-host"
                type="text"
                className="border border-gray-300 rounded px-3 py-2 w-full"
                value={mqttConfig.host}
                onChange={e => setMqttConfig({ ...mqttConfig, host: e.target.value })}
              />
            </div>

            <div>
              <label className="block mb-1" htmlFor="mqtt-port">Porta:</label>
              <input
                id="mqtt-port"
                type="number"
                className="border border-gray-300 rounded px-3 py-2 w-full"
                value={mqttConfig.port}
                onChange={e => setMqttConfig({ ...mqttConfig, port: parseInt(e.target.value || 0) })}
              />
            </div>

            <div>
              <label className="block mb-1" htmlFor="mqtt-username">Utilizador:</label>
              <input
                id="mqtt-username"
                type="text"
                className="border border-gray-300 rounded px-3 py-2 w-full"
                value={mqttConfig.username}
                onChange={e => setMqttConfig({ ...mqttConfig, username: e.target.value })}
              />
            </div>

            <div>
              <label className="block mb-1" htmlFor="mqtt-password">Palavra-passe:</label>
              <input
                id="mqtt-password"
                type="password"
                className="border border-gray-300 rounded px-3 py-2 w-full"
                value={mqttConfig.password}
                onChange={e => setMqttConfig({ ...mqttConfig, password: e.target.value })}
              />
            </div>

            <div>
              <label className="block mb-1" htmlFor="mqtt-topic">Tópico:</label>
              <input
                id="mqtt-topic"
                type="text"
                className="border border-gray-300 rounded px-3 py-2 w-full"
                value={mqttConfig.topic}
                onChange={e => setMqttConfig({ ...mqttConfig, topic: 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>
  );
};

export default Connectivity;
