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";
import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore";
import { useParams } from "react-router-dom";
import { getUserData } from "../../../../../functions/getUserData";
import { useVersionContext } from "../../../../builder/version/versionContext";
import { getWidgetInputData } from "../../../../../services/visulization/zone/getWidgetInputData";

const ProgressCard1 = ({ 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 [value, setValue] = useState<any>("");
  const { selectedChartId } = useWidgetStore();
  const { selectedZone } = useSelectedZoneStore();
  const { projectId } = useParams();
  const { selectedVersionStore } = useVersionContext();
  const { selectedVersion } = selectedVersionStore();

  const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
  const { userName, userId, organization, email } = getUserData();

  useEffect(() => {
    const socket = io(`http://${iotApiUrl}`);
    if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0)
      return;

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

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

    socket.on("connect", startStream);

    socket.on("lastOutput", (response) => {
      const responseData = response.input1;
      setValue(responseData);
    });

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

  const fetchSavedInputes = async () => {
    if (id !== "") {
          let response = await getWidgetInputData(id, selectedZone.zoneUuid, projectId, selectedVersion?.versionId || "")
    
          if (response) {
            setmeasurements(response.Datastructure.measurements)
            setDuration(response.Datastructure.duration)
            setName(response.widgetName)
          }
    }
  };

  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">{value}</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>
  );
};

export default ProgressCard1;
