import { Html } from "@react-three/drei";
import React, { useEffect, useMemo, useState } from "react";
import { Line } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Tooltip,
  ChartData,
  ChartOptions,
} from "chart.js";

import axios from "axios";
import io from "socket.io-client";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
import useChartStore from "../../../../../store/visualization/useChartStore";
import { WavyIcon } from "../../../../../components/icons/3dChartIcons";
import { getUserData } from "../../../../../functions/getUserData";
import { get3dWidgetInput } from "../../../../../services/visulization/zone/get3dWidgetInput";
import { useVersionContext } from "../../../../builder/version/versionContext";
import { useParams } from "react-router-dom";

// Register Chart.js components
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Tooltip
);

// Define Props for SmoothLineGraphComponent
interface SmoothLineGraphProps {
  data: ChartData<"line">; // Type for chart data
  options?: ChartOptions<"line">; // Type for chart options (optional)
}

// SmoothLineGraphComponent using react-chartjs-2
const SmoothLineGraphComponent: React.FC<SmoothLineGraphProps> = ({
  data,
  options,
}) => {
  return <Line data={data} options={options} />;
};
interface ReturnOfInvestmentProps {
  id: string;
  type: string;
  position: [number, number, number];
  rotation: [number, number, number];
  Data?: any;
  onContextMenu?: (event: React.MouseEvent) => void;
}
const ReturnOfInvestment: React.FC<ReturnOfInvestmentProps> = ({
  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 { selectedVersionStore } = useVersionContext();
  const { selectedVersion } = selectedVersionStore();
  const { projectId } = useParams()
  const { userName, userId, organization, email } = getUserData();
  // Improved sample data for the smooth curve graph (single day)
  const graphData: ChartData<"line"> = {
    labels: [
      "12 AM",
      "3 AM",
      "6 AM",
      "9 AM",
      "12 PM",
      "3 PM",
      "6 PM",
      "9 PM",
      "12 AM",
    ],
    datasets: [
      {
        label: "Investment",
        data: [100, 250, 400, 400, 500, 600, 700, 800, 900], // Example investment growth
        borderColor: "rgba(75, 192, 192, 1)", // Light blue color
        backgroundColor: "rgba(75, 192, 192, 0.2)",
        fill: true,
        tension: 0.4, // Smooth curve effect
        pointRadius: 0, // Hide dots
        pointHoverRadius: 0, // Hide hover dots
      },
      {
        label: "Return",
        data: [100, 200, 500, 250, 300, 350, 400, 450, 500], // Example return values
        borderColor: "rgba(255, 99, 132, 1)", // Pink color
        backgroundColor: "rgba(255, 99, 132, 0.2)",
        fill: true,
        tension: 0.4, // Smooth curve effect
        pointRadius: 0, // Hide dots
        pointHoverRadius: 0, // Hide hover dots
      },
    ],
  };

  // Options for the smooth curve graph
  const graphOptions: ChartOptions<"line"> = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      tooltip: {
        enabled: true, // Enable tooltips on hover
        mode: "index", // Show both datasets' values at the same index
        intersect: false, // Allow hovering anywhere on the graph
      },
    },
    scales: {
      x: {
        grid: {
          display: false, // Hide x-axis grid lines
        },
        ticks: {
          display: false, // Hide x-axis labels
        },
      },
      y: {
        grid: {
          display: false, // Hide y-axis grid lines
        },
        ticks: {
          display: false, // Hide y-axis labels
        },
      },
    },
  };

  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, index) => {
        const measurement = measurements[key];
        const datasetKey = `${measurement.name}.${measurement.fields}`;
        return {
          label: datasetKey,
          data: responseData[datasetKey]?.values ?? [],
          borderColor:
            index === 0 ? "rgba(75, 192, 192, 1)" : "rgba(255, 99, 132, 1)", // Light blue color
          backgroundColor:
            index === 0 ? "rgba(75, 192, 192, 0.2)" : "rgba(255, 99, 132, 0.2)",
          fill: true,
          tension: 0.4, // Smooth curve effect
          pointRadius: 0, // Hide dots
          pointHoverRadius: 0, // Hide hover dots
        };
      });

      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 !== "") {
      let response = await get3dWidgetInput(id, organization, projectId, selectedVersion?.versionId || "")
      
      if (response.message === "Widget not found") {
        return
      }

      if (response) {
        setmeasurements(response.Datastructure.measurements);
        setDuration(response.Datastructure.duration);
        setName(response.widgetName);
      }
      // 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) {
      //   echo.error("Failed to fetch saved inputs");
      //   
      // }
    }
  };

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

  useEffect(() => {
    if (selectedChartId?.id === id) {
      fetchSavedInputes();
    }
  }, [chartMeasurements, chartDuration, widgetName]);
  const rotationDegrees = {
    x: (rotation[0] * 180) / Math.PI,
    y: (rotation[1] * 180) / Math.PI,
    z: (rotation[2] * 180) / Math.PI,
  };

  const transformStyle = {
    transform: `rotateX(${rotationDegrees.x}deg) rotateY(${rotationDegrees.y}deg) rotateZ(${rotationDegrees.z}deg)`,
  };

  return (
    <Html
      position={[position[0], position[1], position[2]]}
      rotation={rotation}
      scale={[0.5, 0.5, 0.5]}
      transform
      zIndexRange={[1, 0]}
      prepend
      distanceFactor={20}



    >
      <div
        className={`returnOfInvestment card ${selectedChartId?.id === id ? "activeChart" : ""
          }`}
        onClick={() => setSelectedChartId({ id: id, type: type })}
        onContextMenu={onContextMenu}
      >
        <div className="header">Return of Investment</div>
        <div className="lineGraph charts">
          {/* Smooth curve graph with two datasets */}
          <SmoothLineGraphComponent
            data={Object.keys(measurements).length > 0 ? chartData : graphData}
            options={graphOptions}
          />
        </div>
        <div className="returns-wrapper">
          <div className="icon">
            <WavyIcon />
          </div>
          <div className="value">5.78</div>
          <div className="key">Years</div>
        </div>
        <div className="footer">
          in <span>5y</span> with avg <span>7%</span> yearly return
        </div>
      </div>
    </Html>
  );
};

export default ReturnOfInvestment;
