import { useWidgetStore } from "../../../../store/useWidgetStore";
import ProgressCard from "../2d/charts/ProgressCard";
import PieGraphComponent from "../2d/charts/PieGraphComponent";
import BarGraphComponent from "../2d/charts/BarGraphComponent";
import LineGraphComponent from "../2d/charts/LineGraphComponent";
import DoughnutGraphComponent from "../2d/charts/DoughnutGraphComponent";
import PolarAreaGraphComponent from "../2d/charts/PolarAreaGraphComponent";
import ProgressCard1 from "../2d/charts/ProgressCard1";
import ProgressCard2 from "../2d/charts/ProgressCard2";
import {
  DeleteIcon,
  DublicateIcon,
  KebabIcon,
} from "../../../../components/icons/ExportCommonIcons";
import { useEffect, useRef, useState } from "react";
import { useClickOutside } from "../../functions/handleWidgetsOuterClick";
import { useSocketStore } from "../../../../store/store";
import { usePlayButtonStore } from "../../../../store/usePlayButtonStore";
import OuterClick from "../../../../utils/outerClick";
import useChartStore from "../../../../store/visualization/useChartStore";

type Side = "top" | "bottom" | "left" | "right";

interface Widget {
  id: string;
  type: string;
  title: string;
  panel: Side;
  data: any;
}

export const DraggableWidget = ({
  widget,
  hiddenPanels,
  index,
  onReorder,
  openKebabId,
  setOpenKebabId,
  selectedZone,
  setSelectedZone,
}: {
  selectedZone: {
    zoneName: string;
    zoneId: string;
    activeSides: Side[];
    points: [];
    panelOrder: Side[];
    lockedPanels: Side[];
    widgets: Widget[];
  };
  setSelectedZone: React.Dispatch<
    React.SetStateAction<{
      zoneName: string;
      activeSides: Side[];
      panelOrder: Side[];
      points: [];
      lockedPanels: Side[];
      zoneId: string;
      zoneViewPortTarget: number[];
      zoneViewPortPosition: number[];
      widgets: {
        id: string;
        type: string;
        title: string;
        panel: Side;
        data: any;
      }[];
    }>
  >;

  widget: any;
  hiddenPanels: string[];
  index: number;
  onReorder: (fromIndex: number, toIndex: number) => void;
  openKebabId: string | null;
  setOpenKebabId: (id: string | null) => void;
}) => {
  const { visualizationSocket } = useSocketStore();
  const { selectedChartId, setSelectedChartId } = useWidgetStore();
  const [panelDimensions, setPanelDimensions] = useState<{
    [side in Side]?: { width: number; height: number };
  }>({});
  const { measurements, duration, name } = useChartStore();
  const { isPlaying } = usePlayButtonStore();

  const [canvasDimensions, setCanvasDimensions] = useState({
    width: 0,
    height: 0,
  });
  useEffect(() => {}, [measurements, duration, name]);
  const handlePointerDown = () => {
    if (selectedChartId?.id !== widget.id) {
      setSelectedChartId(widget);
    }
  };

  const chartWidget = useRef<HTMLDivElement>(null);

  const deleteSelectedChart = async () => {
    try {
      console.log("delete");
      
      const email = localStorage.getItem("email") || "";
      const organization = email?.split("@")[1]?.split(".")[0];
      let deleteWidget = {
        zoneId: selectedZone.zoneId,
        widgetID: widget.id,
        organization: organization,
      };

      if (visualizationSocket) {
        setSelectedChartId(null)
        visualizationSocket.emit("v2:viz-widget:delete", deleteWidget);
        console.log("delete widget",selectedChartId);
      }
      const updatedWidgets = selectedZone.widgets.filter(
        (w: Widget) => w.id !== widget.id
      );

      setSelectedZone((prevZone: any) => ({
        ...prevZone,
        widgets: updatedWidgets,
      }));
      setOpenKebabId(null);
      // const response = await deleteWidgetApi(widget.id, organization);
      // if (response?.message === "Widget deleted successfully") {
      //   const updatedWidgets = selectedZone.widgets.filter(
      //     (w: Widget) => w.id !== widget.id
      //   );
      //   setSelectedZone((prevZone: any) => ({
      //     ...prevZone,
      //     widgets: updatedWidgets,
      //   }));
      // }
    } catch (error) {
    } finally {
      setOpenKebabId(null);
    }
  };

  // Calculate panel size
  const panelSize = Math.max(
    Math.min(canvasDimensions.width * 0.25, canvasDimensions.height * 0.25),
    170 // Min 170px
  );

  const getCurrentWidgetCount = (panel: Side) =>
    selectedZone.widgets.filter((w) => w.panel === panel).length;
  // Calculate panel capacity

  const calculatePanelCapacity = (panel: Side) => {
    const CHART_WIDTH = panelSize;
    const CHART_HEIGHT = panelSize;

    const dimensions = panelDimensions[panel];
    if (!dimensions) {
      return panel === "top" || panel === "bottom" ? 5 : 3; // Fallback capacities
    }

    return panel === "top" || panel === "bottom"
      ? Math.max(1, Math.floor(dimensions.width / CHART_WIDTH))
      : Math.max(1, Math.floor(dimensions.height / CHART_HEIGHT));
  };

  const isPanelFull = (panel: Side) => {
    const currentWidgetCount = getCurrentWidgetCount(panel);
    const panelCapacity = calculatePanelCapacity(panel);

    return currentWidgetCount > panelCapacity;
  };

  const duplicateWidget = async () => {
    try {
      const email = localStorage.getItem("email") || "";
      const organization = email?.split("@")[1]?.split(".")[0];

      const duplicatedWidget: Widget = {
        ...widget,
        title: name === '' ? widget.title : name,
        Data: {
          duration: duration,
          measurements: { ...measurements },
        },
        id: `${widget.id}-copy-${Date.now()}`,
      };

      let duplicateWidget = {
        organization: organization,
        zoneId: selectedZone.zoneId,
        widget: duplicatedWidget,
      };
      
      if (visualizationSocket) {
        visualizationSocket.emit("v2:viz-widget:add", duplicateWidget);
      }
      setSelectedZone((prevZone: any) => ({
        ...prevZone,
        widgets: [...prevZone.widgets, duplicatedWidget],
      }));

      // const response = await duplicateWidgetApi(selectedZone.zoneId, organization, duplicatedWidget);

      // if (response?.message === "Widget created successfully") {
      //   setSelectedZone((prevZone: any) => ({
      //     ...prevZone,
      //     widgets: [...prevZone.widgets, duplicatedWidget],
      //   }));
      // }
    } catch (error) {
    } finally {
      setOpenKebabId(null);
    }
  };

  const handleKebabClick = (event: React.MouseEvent<HTMLDivElement>) => {
    event.stopPropagation();
    if (openKebabId === widget.id) {
      setOpenKebabId(null);
    } else {
      setOpenKebabId(widget.id);
    }
  };

  const widgetRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        widgetRef.current &&
        !widgetRef.current.contains(event.target as Node)
      ) {
        setOpenKebabId(null);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [setOpenKebabId]);

  const handleDragStart = (event: React.DragEvent<HTMLDivElement>) => {
    event.dataTransfer.setData("text/plain", index.toString()); // Store the index of the dragged widget
  };
  const handleDragEnter = (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault(); // Allow drop
  };

  const handleDragOver = (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault(); // Allow drop
  };

  const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault();
    const fromIndex = parseInt(event.dataTransfer.getData("text/plain"), 10); // Get the dragged widget's index
    const toIndex = index; // The index of the widget where the drop occurred
    if (fromIndex !== toIndex) {
      onReorder(fromIndex, toIndex); // Call the reorder function passed as a prop
    }
  };

  // useClickOutside(chartWidget, () => {
  //   setSelectedChartId(null);
  // });

  // Track canvas dimensions

  // Current: Two identical useEffect hooks for canvas dimensions
  // Remove the duplicate and keep only one
  useEffect(() => {
    const canvas = document.getElementById("real-time-vis-canvas");
    if (!canvas) return;

    const updateCanvasDimensions = () => {
      const rect = canvas.getBoundingClientRect();
      setCanvasDimensions({
        width: rect.width,
        height: rect.height,
      });
    };

    updateCanvasDimensions();
    const resizeObserver = new ResizeObserver(updateCanvasDimensions);
    resizeObserver.observe(canvas);

    return () => resizeObserver.unobserve(canvas);
  }, []);

  return (
    <>
      <div
        draggable
        key={widget.id}
        className={`chart-container ${
          selectedChartId?.id === widget.id && !isPlaying && "activeChart"
        }`}
        onPointerDown={handlePointerDown}
        onDragStart={handleDragStart}
        onDragEnter={handleDragEnter}
        onDragOver={handleDragOver}
        onDrop={handleDrop}
        style={{
          width: ["top", "bottom"].includes(widget.panel)
            ? `calc(${canvasDimensions.width}px / 6)`
            : undefined,
          height: ["left", "right"].includes(widget.panel)
            ? `calc(${canvasDimensions.height - 15}px / 4)`
            : undefined,
        }}
        ref={chartWidget}
        onClick={() => {setSelectedChartId(widget)
          console.log('click');
          
        }}
      >
        {/* Kebab Icon */}
        <div className="icon kebab" onClick={handleKebabClick}>
          <KebabIcon />
        </div>

        {/* Kebab Options */}
        {openKebabId === widget.id && (
          <div className="kebab-options" ref={widgetRef}>
            <div
              className={`edit btn ${
                isPanelFull(widget.panel) ? "btn-blur" : ""
              }`}
              onClick={duplicateWidget}
            >
              <div className="icon">
                <DublicateIcon />
              </div>
              <div className="label">Duplicate</div>
            </div>
            <div className="edit btn" onClick={(e)=>{
              e.stopPropagation()
              deleteSelectedChart();
            }}>
              <div className="icon">
                <DeleteIcon />
              </div>
              <div className="label">Delete</div>
            </div>
          </div>
        )}

        {/* Render charts based on widget type */}

        {widget.type === "progress 1" && (
          <ProgressCard1 title={widget.title} id={widget.id} />
        )}
        {widget.type === "progress 2" && (
          <ProgressCard2 title={widget.title} id={widget.id} />
        )}
        {widget.type === "line" && (
          <LineGraphComponent
            id={widget.id}
            type={widget.type}
            title={widget.title}
            fontSize={widget.fontSize}
            fontWeight={widget.fontWeight}
          />
        )}
        {widget.type === "bar" && (
          <BarGraphComponent
            id={widget.id}
            type={widget.type}
            title={widget.title}
            fontSize={widget.fontSize}
            fontWeight={widget.fontWeight}
          />
        )}
        {widget.type === "pie" && (
          <PieGraphComponent
            id={widget.id}
            type={widget.type}
            title={widget.title}
            fontSize={widget.fontSize}
            fontWeight={widget.fontWeight}
          />
        )}
        {widget.type === "doughnut" && (
          <DoughnutGraphComponent
            id={widget.id}
            type={widget.type}
            title={widget.title}
            fontSize={widget.fontSize}
            fontWeight={widget.fontWeight}
          />
        )}
        {widget.type === "polarArea" && (
          <PolarAreaGraphComponent
            id={widget.id}
            type={widget.type}
            title={widget.title}
            fontSize={widget.fontSize}
            fontWeight={widget.fontWeight}
          />
        )}
      </div>
    </>
  );
};
