import React, { useState, useEffect } from "react";
import { Line } from "react-chartjs-2";
import useChartStore from "../../../../../store/visualization/useChartStore";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
import axios from "axios";
import io from "socket.io-client";
import { usePlayButtonStore } from "../../../../../store/usePlayButtonStore";

const FleetEfficiencyComponent = ({ object }: any) => {
  const [progress, setProgress] = useState<any>(0);
  const [measurements, setmeasurements] = useState<any>({});
  const [duration, setDuration] = useState("1h");
  const [name, setName] = useState(object.header ? object.header : "");
  const email = localStorage.getItem("email") || "";
  const organization = email?.split("@")[1]?.split(".")[0];
  const { header, flotingDuration, flotingMeasurements } = useChartStore();
  const { selectedChartId } = useWidgetStore();
  const { isPlaying } = usePlayButtonStore();

  const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;

  // Calculate the rotation angle for the progress bar
  const rotationAngle = 45 + progress * 1.8;

  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 responseData = response.input1;
      // console.log(responseData);

      if (typeof responseData === "number") {
        console.log("It's a number!");
        setProgress(responseData);
      }
    });

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

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

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

  useEffect(() => {
    if (selectedChartId?.id === object?.id) {
      fetchSavedInputes();
    }
  }, [header, flotingDuration, flotingMeasurements]);

  return (
    <>
      <h2 className="header">{name}</h2>
      <div
        className="progressContainer"
        style={{ transform: isPlaying ? "skew(-14deg, 0deg)" : "none" }}
      >
        <div className="progress">
          <div className="barOverflow">
            <div
              className="bar"
              style={{ transform: `rotate(${rotationAngle}deg)` }}
            ></div>
          </div>
        </div>
      </div>
      <div className="scaleLabels">
        <span>0%</span>
        <div className="centerText">
          <div className="percentage">{progress}%</div>
          <div className="status">Optimal</div>
        </div>
        <span>100%</span>
      </div>
    </>
  );
};

export default FleetEfficiencyComponent;
