import React, { useState, useEffect } from 'react';
import './App.css';
import mqtt from 'precompiled-mqtt';

function App() {
  const [sensors, setSensors] = useState([]);
  const [brokerUrl, setBrokerUrl] = useState('');

  const topic = 'value/#';
  const client = mqtt.connect(brokerUrl);

  useEffect(() => {
    client.on('connect', () => {
      console.log(`Connected to MQTT broker ${brokerUrl}`);
      client.subscribe(topic, (err) => {
        if (err) {
          console.error('Error subscribing to topic', err);
        } else {
          console.log(`Subscribed to topic ${topic}`);
        }
      });
    });

    client.on('message', (topic, message) => {
      const sensorData = JSON.parse(message.toString());
      setSensors((prevSensors) => {
        const existingSensor = prevSensors.find((sensor) => sensor.id === sensorData.id);
        if (existingSensor) {
          return prevSensors.map((sensor) => (sensor.id === sensorData.id ? sensorData : sensor));
        } else {
          return [...prevSensors, sensorData];
        }
      });
      console.log(`Received sensor data from topic ${topic}:`, sensorData);
    });

    return () => {
      client.end();
    };
  }, [brokerUrl]); // effect will run whenever brokerUrl changes

  const handleUrlChange = (e) => {
    const url = e.target.value;
    setBrokerUrl(url);
  };

  return (
    <div>
      <label htmlFor="url-input">Enter URL of the broker : </label>
      <input id="url-input" type="text" onChange={handleUrlChange} />
      <ul>
        {sensors.map((sensor) => (
          <li key={sensor.id}>
            {sensor.name}: {sensor.value}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;
