import { useEffect } from "react";
import useTemplateStore from "../../../store/useTemplateStore";
import { useSelectedZoneStore } from "../../../store/visualization/useZoneStore";
import { useSocketStore } from "../../../store/store";
import { getTemplateData } from "../../../services/visulization/zone/getTemplate";
import { useDroppedObjectsStore } from "../../../store/visualization/useDroppedObjectsStore";
import RenameInput from "../../../components/ui/inputs/RenameInput";



const Templates = () => {
  const { templates, removeTemplate, setTemplates } = useTemplateStore();
  const { setSelectedZone, selectedZone } = useSelectedZoneStore();
  const { visualizationSocket } = useSocketStore();

  useEffect(() => {
    async function templateData() {
      try {
        const email = localStorage.getItem("email") || "";
        const organization = email?.split("@")[1]?.split(".")[0];
        let response = await getTemplateData(organization);
        setTemplates(response);
      } catch (error) {
        console.error("Error fetching template data:", error);
      }
    }

    templateData();
  }, []);

  const handleDeleteTemplate = async (
    e: React.MouseEvent<HTMLButtonElement>,
    id: string
  ) => {
    try {
      e.stopPropagation();
      const email = localStorage.getItem("email") || "";

      const organization = email?.split("@")[1]?.split(".")[0];
      let deleteTemplate = {
        organization: organization,
        templateID: id,
      };
      if (visualizationSocket) {
        visualizationSocket.emit(
          "v2:viz-template:deleteTemplate",
          deleteTemplate
        );
      }
      removeTemplate(id);
    } catch (error) {
      console.error("Error deleting template:", error);
    }
  };

  const handleLoadTemplate = async (template: any) => {
    try {
      if (selectedZone.zoneName === "") return;
      const email = localStorage.getItem("email") || "";
      const organization = email?.split("@")[1]?.split(".")[0];

      let loadingTemplate = {
        organization: organization,
        zoneId: selectedZone.zoneId,
        templateID: template.id,
      };

      if (visualizationSocket) {
        visualizationSocket.emit("v2:viz-template:addToZone", loadingTemplate);
      }

      setSelectedZone({
        panelOrder: template.panelOrder,
        activeSides: Array.from(new Set(template.panelOrder)), // No merging with previous `activeSides`
        widgets: template.widgets,
      });

      useDroppedObjectsStore
        .getState()
        .setZone(selectedZone.zoneName, selectedZone.zoneId);

      if (Array.isArray(template.floatingWidget)) {
        template.floatingWidget.forEach((val: any) => {
          useDroppedObjectsStore
            .getState()
            .addObject(selectedZone.zoneName, val);
        });
      }
    } catch (error) {
      console.error("Error loading template:", error);
    }
  };

  return (
    <div className="template-list">
      {templates.map((template, index) => (
        <div
          key={template.id}
          className="template-item"
         
        >
          {template?.snapshot && (
            <div className="template-image-container"  onClick={() => handleLoadTemplate(template)}>
              <img
                src={template.snapshot}
                alt={`${template.name} preview`}
                className="template-image"
              />
            </div>
          )}
          <div className="template-details">
            <div className="template-name">
              {/* {`Template ${index + 1}`} */}
              <RenameInput value={`Template ${index + 1}`} />
            </div>
            <button
              onClick={(e) => handleDeleteTemplate(e, template.id)}
              className="delete-button"
              aria-label="Delete template"
            >
              Delete
            </button>
          </div>
        </div>
      ))}
      {templates.length === 0 && (
        <div className="no-templates">
          No saved templates yet. Create one in the visualization view!
        </div>
      )}
    </div>
  );
};

export default Templates;
