import React, { useEffect, useMemo, useState } from "react";
import { Line } from "react-chartjs-2";
import io from "socket.io-client";

import axios from "axios";
import useChartStore from "../../../../../store/visualization/useChartStore";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
import { StockIncreseIcon } from "../../../../../components/icons/RealTimeVisulationIcons";

const ProgressCard2 = ({ id, title }: { id: string; title: string }) => {
  const {
    measurements: chartMeasurements,
    duration: chartDuration,
    name: widgetName,
  } = useChartStore();
  const [measurements, setmeasurements] = useState<any>({});
  const [duration, setDuration] = useState("1h");
  const [name, setName] = useState(title);
  const [value1, setValue1] = useState<any>("");
  const [value2, setValue2] = useState<any>("");
  const { selectedChartId } = useWidgetStore();

  const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
  const email = localStorage.getItem("email") || "";
  const organization = email?.split("@")[1]?.split(".")[0];

  useEffect(() => {
    if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0)
      return;

    const socket = io(`http://${iotApiUrl}`);

    const inputData = {
      measurements,
      duration,
      interval: 1000,
    };

    const startStream = () => {
      socket.emit("lastInput", inputData);
    };

    socket.on("connect", startStream);

    socket.on("lastOutput", (response) => {
      const responseData1 = response.input1;
      const responseData2 = response.input2;
      setValue1(responseData1);
      setValue2(responseData2);
    });

    return () => {
      socket.off("lastOutput");
      socket.emit("stop_stream"); // Stop streaming when component unmounts
      socket.disconnect();
    };
  }, [measurements, duration]);

  const fetchSavedInputes = async () => {
    if (id !== "") {
      try {
        const response = await axios.get(
          `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/WidgetData/${id}/${organization}`
        );
        if (response.status === 200) {
          setmeasurements(response.data.Data.measurements);
          setDuration(response.data.Data.duration);
          setName(response.data.widgetName);
        } else {
          console.log("Unexpected response:", response);
        }
      } catch (error) {
        console.error("There was an error!", error);
      }
    }
  };

  useEffect(() => {
    fetchSavedInputes();
  }, []);

  useEffect(() => {
    if (selectedChartId?.id === id) {
      fetchSavedInputes();
    }
  }, [chartMeasurements, chartDuration, widgetName]);

  return (
    <div className="chart progressBar">
      <div className="header">{name}</div>

      <div className="stock">
        <span className="stock-item">
          <span className="stockValues">
            <div className="value">{value1}</div>
            <div className="key">Units</div>
          </span>
          <div className="stock-description">
            {measurements ? `${measurements?.input1?.fields}` : "description"}
          </div>
        </span>
        <div className="icon">
          <StockIncreseIcon />
        </div>
      </div>

      <div className="stock">
        <span className="stock-item">
          <span className="stockValues">
            <div className="value">{value2}</div>
            <div className="key">Units</div>
          </span>
          <div className="stock-description">
            {measurements ? `${measurements?.input2?.fields}` : "description"}
          </div>
        </span>
        <div className="icon">
          <StockIncreseIcon />
        </div>
      </div>
    </div>
  );
};

export default ProgressCard2;
