import React from "react";
import {
  CleanPannel,
  EyeIcon,
  LockIcon,
} from "../../icons/RealTimeVisulationIcons";
import { panelData } from "../../../services/realTimeVisulization/zoneData/panel";
import { AddIcon } from "../../icons/ExportCommonIcons";

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

// Define the type for the props passed to the Buttons component
interface ButtonsProps {
  selectedZone: {
    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;
    }[];
  };
  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;
      }[];
    }>
  >;
  hiddenPanels: Side[]; // Add this prop for hidden panels
  setHiddenPanels: React.Dispatch<React.SetStateAction<Side[]>>; // Add this prop for updating hidden panels
}

const AddButtons: React.FC<ButtonsProps> = ({
  selectedZone,
  setSelectedZone,
  setHiddenPanels,
  hiddenPanels,
}) => {
  // Local state to track hidden panels

  // Function to toggle lock/unlock a panel
  const toggleLockPanel = (side: Side) => {
    const newLockedPanels = selectedZone.lockedPanels.includes(side)
      ? selectedZone.lockedPanels.filter((panel) => panel !== side)
      : [...selectedZone.lockedPanels, side];

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

    // Update the selectedZone state
    setSelectedZone(updatedZone);
  };

  // Function to toggle visibility of a panel
  const toggleVisibility = (side: Side) => {
    const isHidden = hiddenPanels.includes(side);
    if (isHidden) {
      // If the panel is already hidden, remove it from the hiddenPanels array
      setHiddenPanels(hiddenPanels.filter((panel) => panel !== side));
    } else {
      // If the panel is visible, add it to the hiddenPanels array
      setHiddenPanels([...hiddenPanels, side]);
    }
  };

  // Function to clean all widgets from a panel
  const cleanPanel = (side: Side) => {
    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 = (side: Side) => {
    if (selectedZone.activeSides.includes(side)) {
      // If the panel is already active, remove all widgets and close the panel
      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,
      };

      // Delete the selectedZone state
      setSelectedZone(updatedZone);
    } else {
      const updatePanelData = async () => {
        try {
          // Get email and organization safely
          const email = localStorage.getItem("email") || "";
          const organization = email?.split("@")[1]?.split(".")[0] || "defaultOrg"; // Fallback value

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

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

          // API call
          const response = await panelData(organization, selectedZone.zoneId, newActiveSides);
          

          // Update state
          
          setSelectedZone(updatedZone);
        } catch (error) {
          
        }
      };

      updatePanelData(); // Call the async function
    }


  };

  return (
    <>
      <div>
        {(["top", "right", "bottom", "left"] as Side[]).map((side) => (
          <div key={side} className={`side-button-container ${side}`}>
            {/* "+" Button */}
            <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">
                {/* Hide Panel */}
                <div
                  className={`icon ${hiddenPanels.includes(side) ? "active" : ""
                    }`}
                  title={
                    hiddenPanels.includes(side) ? "Show Panel" : "Hide Panel"
                  }
                  onClick={() => toggleVisibility(side)}
                >
                  <EyeIcon
                    fill={hiddenPanels.includes(side) ? "var(--primary-color)" : "var(--text-color)"}
                  />
                </div>

                {/* Clean Panel */}
                <div
                  className="icon"
                  title="Clean Panel"
                  onClick={() => cleanPanel(side)}
                >
                  <CleanPannel />
                </div>

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

export default AddButtons;
