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

const Settings = () => {
  // Estados para armazenar os valores dos sliders e caixas de entrada
  const [currentLimit, setCurrentLimit] = useState(32);
  const [powerLimit, setPowerLimit] = useState(0);
  const [energyLimit, setEnergyLimit] = useState(0);
  const [chargingTimeLimit, setChargingTimeLimit] = useState(0);
  const [temperatureLimit, setTemperatureLimit] = useState(60);
  const [msg, setMsg] = useState('');
  const [error, setError] = useState('');

  // Função para preencher os campos com os dados do servidor
  const fetchSettings = async () => {
    const response = await fetch('/api/v1/config/settings');
    if (response.ok) {
      const data = await response.json();
      setCurrentLimit(data.currentLimit);
      setPowerLimit(data.powerLimit);
      setEnergyLimit(data.energyLimit);
      setChargingTimeLimit(data.chargingTimeLimit);
      setTemperatureLimit(data.temperatureLimit);
    } else {
      setError('Erro ao obter as configurações');
    }
  };

  // Carregar as configurações ao montar o componente
  useEffect(() => {
    fetchSettings();
  }, []);

  const handleCurrentLimitChange = (e) => setCurrentLimit(parseInt(e.target.value, 10));
  const handlePowerLimitChange = (e) => setPowerLimit(parseInt(e.target.value, 10));
  const handleEnergyLimitChange = (e) => setEnergyLimit(parseInt(e.target.value, 10));
  const handleChargingTimeLimitChange = (e) => setChargingTimeLimit(parseInt(e.target.value, 10));
  const handleTemperatureLimitChange = (e) => setTemperatureLimit(parseInt(e.target.value, 10));

  const handleSubmit = async (e) => {
    e.preventDefault();
    const settingsData = {
      currentLimit,
      powerLimit,
      energyLimit,
      chargingTimeLimit,
      temperatureLimit,
    };

    try {
      const response = await fetch('/api/v1/config/settings', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(settingsData),
      });

      if (response.ok) {
        setMsg('Alterações guardadas com sucesso!');
      } else {
        setError('Erro ao guardar alterações.');
      }
    } catch {
      setError('Erro ao guardar alterações.');
    }
  };

  return (
    <PageLayout title="Definições de Energia">
      {msg && <Alert type="success">{msg}</Alert>}
      {error && <Alert type="error">{error}</Alert>}

      <form className="flex flex-col gap-4" onSubmit={handleSubmit}>
        <div>
          <label className="block mb-1" htmlFor="currentLimit">Limite de Corrente (A):</label>
          <input
            id="currentLimit"
            type="number"
            className="border border-gray-300 rounded px-3 py-2 w-full"
            value={currentLimit}
            onChange={handleCurrentLimitChange}
          />
        </div>

        <div>
          <label className="block mb-1" htmlFor="powerLimit">Limite de Potência (W):</label>
          <input
            id="powerLimit"
            type="number"
            className="border border-gray-300 rounded px-3 py-2 w-full"
            value={powerLimit}
            onChange={handlePowerLimitChange}
          />
        </div>

        <div>
          <label className="block mb-1" htmlFor="energyLimit">Limite de Energia (kWh):</label>
          <input
            id="energyLimit"
            type="number"
            className="border border-gray-300 rounded px-3 py-2 w-full"
            value={energyLimit}
            onChange={handleEnergyLimitChange}
          />
        </div>

        <div>
          <label className="block mb-1" htmlFor="chargingTimeLimit">Tempo Máximo de Carregamento (min):</label>
          <input
            id="chargingTimeLimit"
            type="number"
            className="border border-gray-300 rounded px-3 py-2 w-full"
            value={chargingTimeLimit}
            onChange={handleChargingTimeLimitChange}
          />
        </div>

        <div>
          <label className="block mb-1" htmlFor="temperatureLimit">Temperatura Máxima (°C):</label>
          <input
            id="temperatureLimit"
            type="number"
            className="border border-gray-300 rounded px-3 py-2 w-full"
            value={temperatureLimit}
            onChange={handleTemperatureLimitChange}
          />
        </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 Settings;
