import React from "react";
import {
  CleanPannel,
  EyeIcon,
  LockIcon,
} from "../../../../components/icons/RealTimeVisulationIcons";
import { AddIcon } from "../../../../components/icons/ExportCommonIcons";
import { useSocketStore } from "../../../../store/builder/store";
import { useParams } from "react-router-dom";
import { getUserData } from "../../../../functions/getUserData";
import { useVersionContext } from "../../../builder/version/versionContext";

// 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 {
  [zoneUuid: 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: [];
    zoneUuid: 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: [];
      zoneUuid: 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();
  const { projectId } = useParams();
  const { userId, organization, email } = getUserData();
  const { selectedVersionStore } = useVersionContext();
  const { selectedVersion } = selectedVersionStore();

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

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

  // Function to toggle lock/unlock a panel
  const toggleLockPanel = async (side: Side) => {
    //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,
      lockedPanel: newLockedPanels,
      zoneUuid: selectedZone.zoneUuid,
      versionId: selectedVersion?.versionId || '',
      projectId,
      userId
    };
    if (visualizationSocket) {
      visualizationSocket.emit("v1: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.zoneUuid]?.includes(side) ||
      selectedZone.lockedPanels.includes(side)
    )
      return;



    let clearPanel = {
      organization,
      panelName: side,
      zoneUuid: selectedZone.zoneUuid,
      versionId: selectedVersion?.versionId || '',
      projectId,
      userId,
    };
    if (visualizationSocket) {
      visualizationSocket.emit("v1: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 zoneUuid = selectedZone.zoneUuid;

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

      setWaitingPanels(side); // Mark as waiting

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

        // 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,
          zoneUuid,
          projectId,
          versionId: selectedVersion?.versionId || '',
          userId
        };

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

        setSelectedZone(updatedZone);

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

        // Remove from waiting state
        setWaitingPanels(null);
      }, 500); // Wait for 2 seconds
    } else {
      // Panel does not exist: Add it
      try {
        const newActiveSides = selectedZone.activeSides.includes(side)
          ? [...selectedZone.activeSides]
          : [...selectedZone.activeSides, side];

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

        const addPanel = {
          organization,
          zoneUuid,
          projectId,
          versionId: selectedVersion?.versionId || '',
          userId,
          panelOrder: newActiveSides,
        };

        if (visualizationSocket) {
          visualizationSocket.emit("v1: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={`${side}-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.zoneUuid]?.includes(side) &&
                  waitingPanels !== side
                  ? "extra-Bs-addopening"
                  : ""
                }
                `}
            >
              {/* Hide Panel */}
              <button
                className={`icon ${hiddenPanels[selectedZone.zoneUuid]?.includes(side)
                  ? "active"
                  : ""
                  }`}
                id={`${side}-hide-panel-visulization`}
                title={
                  hiddenPanels[selectedZone.zoneUuid]?.includes(side)
                    ? "Show Panel"
                    : "Hide Panel"
                }
                onClick={() => toggleVisibility(side)}
              >
                <EyeIcon
                  fill={
                    hiddenPanels[selectedZone.zoneUuid]?.includes(side)
                      ? "var(--icon-default-color-active)"
                      : "var(--text-color)"
                  }
                />
              </button>

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

              {/* Lock/Unlock Panel */}
              <button
                className={`icon ${selectedZone.lockedPanels.includes(side) ? "active" : ""
                  }`}
                id={`${side}-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;
