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

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;
    activeSides: Side[];
    panelOrder: Side[];
    lockedPanels: Side[];
    widgets: Widget[];
  };
  setSelectedZone: React.Dispatch<
    React.SetStateAction<{
      zoneName: string;
      activeSides: Side[];
      panelOrder: Side[];
      lockedPanels: Side[];
      widgets: Widget[];
    }>
  >;
  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 = () => {
    const updatedWidgets = selectedZone.widgets.filter(
      (w: Widget) => w.id !== widget.id
    );

    setSelectedZone((prevZone: any) => ({
      ...prevZone,
      widgets: updatedWidgets,
    }));

    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 = () => {
    const duplicatedWidget: Widget = {
      ...widget,
      id: `${widget.id}-copy-${Date.now()}`,
    };

    setSelectedZone((prevZone: any) => ({
      ...prevZone,
      widgets: [...prevZone.widgets, duplicatedWidget],
    }));

    setOpenKebabId(null);

    console.log("Duplicated widget with ID:", duplicatedWidget.id);
  };

  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]);

  return (
    <>
      <div
        draggable
        key={widget.id}
        className={`chart-container ${
          selectedChartId?.id === widget.id && "activeChart"
        }`}
        onPointerDown={handlePointerDown}
        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
            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
            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
            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
            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 === "polarArea" && (
          <PolarAreaGraphComponent
            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",
            }}
          />
        )}
      </div>
    </>
  );
};
