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

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

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

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

  // Carregar as configurações Wi-Fi e MQTT
  useEffect(() => {
    const load = async () => {

      try {
        const wifi = await get('/api/v1/config/wifi');
        setWifiConfig(wifi);  // Atualiza as configurações Wi-Fi
      } catch (error) {
        console.error('Erro ao carregar configurações Wi-Fi:', error);
      }

      try {
        const mqtt = await get('/api/v1/config/mqtt');
        setMqttConfig(mqtt);  // Atualiza as configurações MQTT
      } catch (error) {
        console.error('Erro ao carregar configurações MQTT:', error);
      }

      setLoading(false);  // Finaliza o carregamento
    };

    load();
  }, []);

  // Salvar configuração Wi-Fi
  const saveWifi = async () => {
    try {
      await post('/api/v1/config/wifi', wifiConfig);
      setWifiMsg('Alterações guardadas com sucesso!');
    } catch (error) {
      setWifiMsg('Erro ao guardar alterações.');
    }
  };

  // Salvar configuração MQTT
  const saveMqtt = async () => {
    try {
      await post('/api/v1/config/mqtt', mqttConfig);
      setMqttMsg('Alterações guardadas com sucesso!');
    } catch (error) {
      setMqttMsg('Erro ao guardar alterações.');
    }
  };

  return (
    <PageLayout title="Conectividade">
      {loading ? (
        <p>A carregar...</p>
      ) : (


          <h2 className="text-xl font-semibold mt-4">Configuração Wi-Fi</h2>
          {wifiMsg && <Alert type={wifiMsg.startsWith('Erro') ? 'error' : 'success'}>{wifiMsg}</Alert>}
          <form className="flex flex-col gap-4" onSubmit={e => { e.preventDefault(); saveWifi(); }}>


          <div>
              <label className="flex items-center gap-2">
                Ativar WIFI
                <input
                  type="checkbox"
                  checked={wifiConfig.enabled}
                  onChange={e => setMqttConfig({ ...wifiConfig, enabled: e.target.checked })}
                />
              </label>
            </div>

            <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 && <Alert type={mqttMsg.startsWith('Erro') ? 'error' : 'success'}>{mqttMsg}</Alert>}
          <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;
