import React from "react";
import {
  CleanPannel,
  EyeIcon,
  LockIcon,
} from "../../../../components/icons/RealTimeVisulationIcons";
import { AddIcon } from "../../../../components/icons/ExportCommonIcons";
import { useSocketStore } from "../../../../store/builder/store";

// Define the type for `Side`
type Side = "top" | "bottom" | "left" | "right";

// Define the type for HiddenPanels, where keys are zone IDs and values are arrays of hidden sides
interface HiddenPanels {
  [zoneId: string]: Side[];
}

// Define the type for the props passed to the Buttons component
interface ButtonsProps {
  selectedZone: {
    zoneName: string;
    activeSides: Side[];
    panelOrder: Side[];
    lockedPanels: Side[];
    points: [];
    zoneId: string;
    zoneViewPortTarget: number[];
    zoneViewPortPosition: number[];
    widgets: {
      id: string;
      type: string;
      title: string;
      panel: Side;
      data: any;
    }[];
  };
  setSelectedZone: React.Dispatch<
    React.SetStateAction<{
      zoneName: string;
      activeSides: Side[];
      panelOrder: Side[];
      lockedPanels: Side[];
      points: [];
      zoneId: string;
      zoneViewPortTarget: number[];
      zoneViewPortPosition: number[];
      widgets: {
        id: string;
        type: string;
        title: string;
        panel: Side;
        data: any;
      }[];
    }>
  >;
  hiddenPanels: HiddenPanels; // Updated prop type
  setHiddenPanels: React.Dispatch<React.SetStateAction<HiddenPanels>>; // Updated prop type
  waitingPanels: any;
  setWaitingPanels: any;
}

const AddButtons: React.FC<ButtonsProps> = ({
  selectedZone,
  setSelectedZone,
  setHiddenPanels,
  hiddenPanels,
  waitingPanels,
  setWaitingPanels,
}) => {
  const { visualizationSocket } = useSocketStore();

  // Function to toggle visibility of a panel
  const toggleVisibility = (side: Side) => {
    const isHidden = hiddenPanels[selectedZone.zoneId]?.includes(side) ?? false;

    if (isHidden) {
      // If the panel is already hidden, remove it from the hiddenPanels array for this zone
      setHiddenPanels((prevHiddenPanels) => ({
        ...prevHiddenPanels,
        [selectedZone.zoneId]: prevHiddenPanels[selectedZone.zoneId].filter(
          (panel) => panel !== side
        ),
      }));
    } else {
      // If the panel is visible, add it to the hiddenPanels array for this zone
      setHiddenPanels((prevHiddenPanels) => ({
        ...prevHiddenPanels,
        [selectedZone.zoneId]: [
          ...(prevHiddenPanels[selectedZone.zoneId] || []),
          side,
        ],
      }));
    }
  };

  // Function to toggle lock/unlock a panel
  const toggleLockPanel = async (side: Side) => {
    const email = localStorage.getItem("email") ?? "";
    const organization = email?.split("@")[1]?.split(".")[0]; // Fallback value
    //add api
    const newLockedPanels = selectedZone.lockedPanels.includes(side)
      ? selectedZone.lockedPanels.filter((panel) => panel !== side)
      : [...selectedZone.lockedPanels, side];

    const updatedZone = {
      ...selectedZone,
      lockedPanels: newLockedPanels,
    };

    let lockedPanel = {
      organization: organization,
      lockedPanel: newLockedPanels,
      zoneId: selectedZone.zoneId,
    };
    if (visualizationSocket) {
      visualizationSocket.emit("v2:viz-panel:locked", lockedPanel);
    }

    setSelectedZone(updatedZone);
  };

  // Function to clean all widgets from a panel
  const cleanPanel = async (side: Side) => {
    //add api
    // console.log('side: ', side);
    if (
      hiddenPanels[selectedZone.zoneId]?.includes(side) ||
      selectedZone.lockedPanels.includes(side)
    )
      return;

    const email = localStorage.getItem("email") ?? "";
    const organization = email?.split("@")[1]?.split(".")[0]; // Fallback value

    let clearPanel = {
      organization: organization,
      panelName: side,
      zoneId: selectedZone.zoneId,
    };
    if (visualizationSocket) {
      visualizationSocket.emit("v2:viz-panel:clear", clearPanel);
    }
    const cleanedWidgets = selectedZone.widgets.filter(
      (widget) => widget.panel !== side
    );
    const updatedZone = {
      ...selectedZone,
      widgets: cleanedWidgets,
    };
    // Update the selectedZone state
    setSelectedZone(updatedZone);
  };

  // Function to handle "+" button click
  const handlePlusButtonClick = async (side: Side) => {
    const zoneId = selectedZone.zoneId;

    if (selectedZone.activeSides.includes(side)) {
      // Already active: Schedule removal

      setWaitingPanels(side); // Mark as waiting

      setTimeout(() => {
        console.log("Removing after wait...");

        const email = localStorage.getItem("email") ?? "";
        const organization = email?.split("@")[1]?.split(".")[0] ?? "";

        // Remove widgets for that side
        const cleanedWidgets = selectedZone.widgets.filter(
          (widget) => widget.panel !== side
        );
        const newActiveSides = selectedZone.activeSides.filter(
          (s) => s !== side
        );

        const updatedZone = {
          ...selectedZone,
          widgets: cleanedWidgets,
          activeSides: newActiveSides,
          panelOrder: newActiveSides,
        };

        const deletePanel = {
          organization,
          panelName: side,
          zoneId,
        };

        if (visualizationSocket) {
          visualizationSocket.emit("v2:viz-panel:delete", deletePanel);
        }

        setSelectedZone(updatedZone);

        if (hiddenPanels[zoneId]?.includes(side)) {
          setHiddenPanels((prev) => ({
            ...prev,
            [zoneId]: prev[zoneId].filter((s) => s !== side),
          }));
        }

        // Remove from waiting state
        setWaitingPanels(null);
      }, 500); // Wait for 2 seconds
    } else {
      // Panel does not exist: Add it
      try {
        const email = localStorage.getItem("email") ?? "";
        const organization = email?.split("@")[1]?.split(".")[0] ?? "";

        const newActiveSides = selectedZone.activeSides.includes(side)
          ? [...selectedZone.activeSides]
          : [...selectedZone.activeSides, side];

        const updatedZone = {
          ...selectedZone,
          activeSides: newActiveSides,
          panelOrder: newActiveSides,
        };

        const addPanel = {
          organization,
          zoneId,
          panelOrder: newActiveSides,
        };

        if (visualizationSocket) {
          visualizationSocket.emit("v2:viz-panel:add", addPanel);
        }

        setSelectedZone(updatedZone);
      } catch (error) {
        echo.error("Failed to adding panel");
        console.error("Error adding panel:", error);
      }
    }
  };

  return (
    <div>
      {(["top", "right", "bottom", "left"] as Side[]).map((side) => (
        <div key={side} className={`side-button-container ${side}`}>
          {/* "+" Button */}

          <button
            id="panel-add-button"
            className={`side-button ${side}${
              selectedZone.activeSides.includes(side) ? " active" : ""
            }`}
            onClick={() => handlePlusButtonClick(side)}
            title={
              selectedZone.activeSides.includes(side)
                ? `Remove all items and close ${side} panel`
                : `Activate ${side} panel`
            }
          >
            <div className="add-icon">
              <AddIcon />
            </div>
          </button>

          {/* Extra Buttons */}
          {selectedZone.activeSides.includes(side) && (
            <div
              className={`extra-Bs
                  ${waitingPanels === side ? "extra-Bs-addclosing" : ""}
                  ${
                    !hiddenPanels[selectedZone.zoneId]?.includes(side) &&
                    waitingPanels !== side
                      ? "extra-Bs-addopening"
                      : ""
                  }
                `}
            >
              {/* Hide Panel */}
              <button
                className={`icon ${
                  hiddenPanels[selectedZone.zoneId]?.includes(side)
                    ? "active"
                    : ""
                }`}
                id="hide-panel-visulization"
                title={
                  hiddenPanels[selectedZone.zoneId]?.includes(side)
                    ? "Show Panel"
                    : "Hide Panel"
                }
                onClick={() => toggleVisibility(side)}
              >
                <EyeIcon
                  fill={
                    hiddenPanels[selectedZone.zoneId]?.includes(side)
                      ? "var(--icon-default-color-active)"
                      : "var(--text-color)"
                  }
                />
              </button>

              {/* Clean Panel */}
              <button
                className="icon"
                title="Clean Panel"
                id="clean-panel-visulization"
                onClick={() => cleanPanel(side)}
                style={{
                  cursor:
                    hiddenPanels[selectedZone.zoneId]?.includes(side) ||
                    selectedZone.lockedPanels.includes(side)
                      ? "not-allowed"
                      : "pointer",
                }}
              >
                <CleanPannel />
              </button>

              {/* Lock/Unlock Panel */}
              <button
                className={`icon ${
                  selectedZone.lockedPanels.includes(side) ? "active" : ""
                }`}
                id="lock-panel-visulization"
                title={
                  selectedZone.lockedPanels.includes(side)
                    ? "Unlock Panel"
                    : "Lock Panel"
                }
                onClick={() => toggleLockPanel(side)}
              >
                <LockIcon
                  fill={
                    selectedZone.lockedPanels.includes(side)
                      ? "var(--icon-default-color-active)"
                      : "var(--text-color)"
                  }
                />
              </button>
            </div>
          )}
        </div>
      ))}
    </div>
  );
};

export default AddButtons;
