import React from "react";
import {
  CleanPannel,
  EyeIcon,
  LockIcon,
} from "../../icons/RealTimeVisulationIcons";
import { AddIcon } from "../../icons/ExportCommonIcons";
import { useSocketStore } from "../../../store/store";
import { clearPanel } from "../../../services/realTimeVisulization/zoneData/clearPanel";
import { lockPanel } from "../../../services/realTimeVisulization/zoneData/lockPanel";

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

const AddButtons: React.FC<ButtonsProps> = ({
  selectedZone,
  setSelectedZone,
  setHiddenPanels,
  hiddenPanels,
}) => {
  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) => {
    // console.log('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);
    // let response = await lockPanel(selectedZone.zoneId, organization, newLockedPanels)
    // console.log('response: ', response);
    // if (response.message === 'locked panel updated successfully') {
    //   // Update the selectedZone state
    //   setSelectedZone(updatedZone);
    // }
  };

  // Function to clean all widgets from a panel
  const cleanPanel = async (side: Side) => {
    //add api
    // console.log('side: ', side);
    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
    // console.log('updatedZone: ', updatedZone);
    setSelectedZone(updatedZone);

    // let response = await clearPanel(selectedZone.zoneId, organization, side)
    // console.log('response: ', response);
    // if (response.message === 'PanelWidgets cleared successfully') {

    //   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) => {
    if (selectedZone.activeSides.includes(side)) {
      console.log("open");
      // Panel already exists: Remove widgets from that side and update activeSides
      const email = localStorage.getItem("email") || "";
      const organization = email?.split("@")[1]?.split(".")[0]; // Fallback value

      // Remove all widgets associated with the side and update active sides
      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,
      };

      let deletePanel = {
        organization: organization,
        panelName: side,
        zoneId: selectedZone.zoneId,
      };
      if (visualizationSocket) {
        visualizationSocket.emit("v2:viz-panel:delete", deletePanel);
      }
      setSelectedZone(updatedZone);



      if (hiddenPanels[selectedZone.zoneId]?.includes(side)) {

        setHiddenPanels(prev => ({
          ...prev,
          [selectedZone.zoneId]: prev[selectedZone.zoneId].filter(s => s !== side)
        }));
      }

      // if(hiddenPanels[selectedZone.zoneId].includes(side))

      // API call to delete the panel
      // try {
      //   const response = await deletePanelApi(selectedZone.zoneId, side, organization);
      //
      //   if (response.message === "Panel deleted successfully") {
      //   } else {
      //
      //   }
      // } catch (error) {
      //
      // }
    } else {
      // Panel does not exist: Create panel
      try {
        // Get email and organization safely with a default fallback
        const email = localStorage.getItem("email") || "";
        const organization = email?.split("@")[1]?.split(".")[0];

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

        const updatedZone = {
          ...selectedZone,
          activeSides: newActiveSides,
          panelOrder: newActiveSides,
        };
        let addPanel = {
          organization: organization,
          zoneId: selectedZone.zoneId,
          panelOrder: newActiveSides,
        };
        if (visualizationSocket) {
          visualizationSocket.emit("v2:viz-panel:add", addPanel);
        }
        setSelectedZone(updatedZone);
        // API call to create panels
        // const response = await panelData(organization, selectedZone.zoneId, newActiveSides);
        //

        // if (response.message === "Panels created successfully") {
        // } else {
        //
        // }
      } catch (error) {}
    }
  };
  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[selectedZone.zoneId]?.includes(side)
                    ? "active"
                    : ""
                    }`}
                  title={
                    hiddenPanels[selectedZone.zoneId]?.includes(side)
                      ? "Show Panel"
                      : "Hide Panel"
                  }
                  onClick={() => toggleVisibility(side)}
                >
                  <EyeIcon
                    fill={
                      hiddenPanels[selectedZone.zoneId]?.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;
