import { useWidgetStore } from "../../../store/useWidgetStore";
import ProgressCard from "../realTimeVis/charts/ProgressCard";
import PieGraphComponent from "../realTimeVis/charts/PieGraphComponent";
import BarGraphComponent from "../realTimeVis/charts/BarGraphComponent";
import LineGraphComponent from "../realTimeVis/charts/LineGraphComponent";
import DoughnutGraphComponent from "../realTimeVis/charts/DoughnutGraphComponent";
import PolarAreaGraphComponent from "../realTimeVis/charts/PolarAreaGraphComponent";
import {
  DeleteIcon,
  DublicateIcon,
  KebabIcon,
} from "../../icons/ExportCommonIcons";
import { useEffect, useRef, useState } from "react";
import { duplicateWidgetApi } from "../../../services/realTimeVisulization/zoneData/duplicateWidget";
import { deleteWidgetApi } from "../../../services/realTimeVisulization/zoneData/deleteWidgetApi";

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[];
    panelOrder: Side[];
    lockedPanels: Side[];
    widgets: Widget[];
  };
  setSelectedZone: React.Dispatch<
    React.SetStateAction<{
      zoneName: string;
      activeSides: Side[];
      panelOrder: Side[];

      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 { selectedChartId, setSelectedChartId } = useWidgetStore();
  const [panelDimensions, setPanelDimensions] = useState<{
    [side in Side]?: { width: number; height: number };
  }>({});
  const handlePointerDown = () => {
    if (selectedChartId?.id !== widget.id) {
      setSelectedChartId(widget);
    }
  };

  const isPanelHidden = hiddenPanels.includes(widget.panel);

  const deleteSelectedChart = async () => {
    try {
      const email = localStorage.getItem("email") || "";
      const organization = email?.split("@")[1]?.split(".")[0];
      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);
    }
  };


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

  const calculatePanelCapacity = (panel: Side) => {
    const CHART_WIDTH = 150;
    const CHART_HEIGHT = 150;
    const FALLBACK_HORIZONTAL_CAPACITY = 5;
    const FALLBACK_VERTICAL_CAPACITY = 3;

    const dimensions = panelDimensions[panel];
    if (!dimensions) {
      return panel === "top" || panel === "bottom"
        ? FALLBACK_HORIZONTAL_CAPACITY
        : FALLBACK_VERTICAL_CAPACITY;
    }

    return panel === "top" || panel === "bottom"
      ? Math.floor(dimensions.width / CHART_WIDTH)
      : 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,
        id: `${widget.id}-copy-${Date.now()}`,
      };

      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
    }
  };

  return (
    <>
      <div
        draggable
        key={widget.id}
        className={`chart-container ${selectedChartId?.id === widget.id && "activeChart"
          }`}
        onPointerDown={handlePointerDown}
        onDragStart={handleDragStart}
        onDragEnter={handleDragEnter}
        onDragOver={handleDragOver}
        onDrop={handleDrop}
        style={{
          opacity: isPanelHidden ? 0 : 1,
          pointerEvents: isPanelHidden ? "none" : "auto",
        }}
      >
        {/* 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={isPanelFull(widget.panel) ? undefined : duplicateWidget}
            >
              <div className="icon">
                <DublicateIcon />
              </div>
              <div className="label">Duplicate</div>
            </div>
            <div className="edit btn" onClick={deleteSelectedChart}>
              <div className="icon">
                <DeleteIcon />
              </div>
              <div className="label">Delete</div>
            </div>
          </div>
        )}

        {/* Render charts based on widget type */}
        
        {widget.type === "progress" && (
          <ProgressCard title={widget.title} data={widget.data} />
        )}
        {widget.type === "line" && (
          <LineGraphComponent
            id={widget.id}
            type={widget.type}
            title={widget.title}
            fontSize={widget.fontSize}
            fontWeight={widget.fontWeight}
            // data={{
            //   measurements: [
            //     { name: "testDevice", fields: "powerConsumption" },
            //     { name: "furnace", fields: "powerConsumption" },
            //   ],
            //   interval: 1000,
            //   duration: "1h",
            // }}
          />
        )}
        {widget.type === "bar" && (
          <BarGraphComponent
            id={widget.id}
            type={widget.type}
            title={widget.title}
            fontSize={widget.fontSize}
            fontWeight={widget.fontWeight}
            // data={{
            //   measurements: [
            //     { name: "testDevice", fields: "powerConsumption" },
            //     { name: "furnace", fields: "powerConsumption" },
            //   ],
            //   interval: 1000,
            //   duration: "1h",
            // }}
          />
        )}
        {widget.type === "pie" && (
          <PieGraphComponent
            id={widget.id}
            type={widget.type}
            title={widget.title}
            fontSize={widget.fontSize}
            fontWeight={widget.fontWeight}
            // data={{
            //   measurements: [
            //     { name: "testDevice", fields: "powerConsumption" },
            //     { name: "furnace", fields: "powerConsumption" },
            //   ],
            //   interval: 1000,
            //   duration: "1h",
            // }}
          />
        )}
        {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>
    </>
  );
};
