import { Html } from "@react-three/drei";
import React, { useEffect, useMemo, useState } from "react";
import { Bar } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
  TooltipItem, // Import TooltipItem for typing
} from "chart.js";

import axios from "axios";
import io from "socket.io-client";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
import useChartStore from "../../../../../store/visualization/useChartStore";

// Register ChartJS components
ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);
interface ProductionCapacityProps {
  id: string;
  type: string;
  position: [number, number, number];
  rotation: [number, number, number];
  Data?: any,
  onContextMenu?: (event: React.MouseEvent) => void;
  // onPointerDown:any
}

const ProductionCapacity: React.FC<ProductionCapacityProps> = ({
  id,
  type,
  Data,
  position,
  rotation,
  onContextMenu,
}) => {
  const { selectedChartId, setSelectedChartId } = useWidgetStore();
  const {
    measurements: chartMeasurements,
    duration: chartDuration,
    name: widgetName,
  } = useChartStore();
  const [measurements, setmeasurements] = useState<any>(Data?.measurements ? Data.measurements : {});
  const [duration, setDuration] = useState(Data?.duration ? Data.duration : "1h");
  const [name, setName] = useState("Widget");
  const [chartData, setChartData] = useState<{
    labels: string[];
    datasets: any[];
  }>({
    labels: [],
    datasets: [],
  });
  const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
  const email = localStorage.getItem("email") || "";
  const organization = email?.split("@")[1]?.split(".")[0];
  // Chart data for a week
  const defaultChartData = {
    labels: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], // Days of the week
    datasets: [
      {
        label: "Production Capacity (units/day)",
        data: [1500, 1600, 1400, 1700, 1800, 1900, 2000], // Example daily production data
        backgroundColor: "#6f42c1", // Theme color
        borderColor: "#6f42c1",
        borderWidth: 1,
        borderRadius: 8, // Rounded corners for the bars
        borderSkipped: false, // Ensure all corners are rounded
      },
    ],
  };

  // Chart options
  const chartOptions = {
    responsive: true,
    plugins: {
      legend: {
        display: false, // Hide legend
      },
      title: {
        display: true,
        text: "Weekly Production Capacity",
        font: {
          size: 16,
        },
      },
      tooltip: {
        callbacks: {
          // Explicitly type the context parameter
          label: (context: TooltipItem<"bar">) => {
            const value = context.parsed.y; // Extract the y-axis value
            return `${value} units`; // Customize tooltip to display "units"
          },
        },
      },
    },
    scales: {
      x: {
        grid: {
          display: false, // Hide x-axis grid lines
        },
      },
      y: {
        display: false, // Remove the y-axis completely
      },
    },
  };

  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("lineInput", inputData);
    };

    socket.on("connect", startStream);

    socket.on("lineOutput", (response) => {
      const responseData = response.data;

      // Extract timestamps and values
      const labels = responseData.time;
      const datasets = Object.keys(measurements).map((key) => {
        const measurement = measurements[key];
        const datasetKey = `${measurement.name}.${measurement.fields}`;
        return {
          label: datasetKey,
          data: responseData[datasetKey]?.values ?? [],
          backgroundColor: "#6f42c1", // Theme color
          borderColor: "#6f42c1",
          borderWidth: 1,
          borderRadius: 8, // Rounded corners for the bars
          borderSkipped: false, // Ensure all corners are rounded
        };
      });

      setChartData({ labels, datasets });
    });

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

  const fetchSavedInputes = async () => {
    if (id !== "") {
      try {
        const response = await axios.get(
          `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/widget3D/${id}/${organization}`
        );

        if (response.status === 200) {
          setmeasurements(response.data.Data.measurements);
          setDuration(response.data.Data.duration);
          setName(response.data.widgetName);
        } else {
        }
      } catch (error) { }
    }
  };

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

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

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



  return (

    <Html
      position={position}
      scale={[0.5, 0.5, 0.5]}
      rotation={rotation}
      transform
      sprite={false}
      zIndexRange={[1, 0]}
      // style={{
      //   transform: transformStyle.transform,
      //   transformStyle: "preserve-3d",
      //   transition: "transform 0.1s ease-out",
      // }}
      onDragOver={(e) => {
        e.preventDefault();
        e.stopPropagation();
      }}
      onDrop={(e) => {
        e.preventDefault();
        // e.stopPropagation();
      }}
      wrapperClass="pointer-none"

    >
      <div
        className={`productionCapacity-wrapper card ${selectedChartId?.id === id ? "activeChart" : ""}`}
        onClick={() => setSelectedChartId({ id: id, type: type })}
        onContextMenu={onContextMenu}

        style={{
          width: "300px", // Original width
          height: "300px", // Original height
          // transform: transformStyle.transform,
          transformStyle: "preserve-3d",
          position: "absolute",
          transform:'translate(-50%, -50%)',
        }}
      >
        <div className="headeproductionCapacityr-wrapper">
          <div className="header">Production Capacity</div>
          <div className="production-capacity">
            <div className="value">1,200</div>{" "}
            <div className="value">units/hour</div>
          </div>
          <div className="production-capacity">
            <div className="current">
              <div className="key">Current</div>
              <div className="value">1500</div>
            </div>
            <div className="target">
              <div className="key">Target</div>
              <div className="value">2.345</div>
            </div>
            {/* <div className="value">units/hour</div> */}
          </div>
        </div>{" "}
        <div className="bar-chart charts">
          {/* Bar Chart */}
          <Bar
            data={
              Object.keys(measurements).length > 0
                ? chartData
                : defaultChartData
            }
            options={chartOptions}
          />
        </div>
      </div>
    </Html>

  );
};

export default ProductionCapacity;
