import { useEffect } from "react";
import useTemplateStore from "../../../store/useTemplateStore";
import { useSelectedZoneStore } from "../../../store/visualization/useZoneStore";
import { useSocketStore } from "../../../store/builder/store";
import { getTemplateData } from "../../../services/visulization/zone/getTemplate";
import { useDroppedObjectsStore } from "../../../store/visualization/useDroppedObjectsStore";
import RenameInput from "../../../components/ui/inputs/RenameInput";
import { useParams } from "react-router-dom";
import { getUserData } from "../../../functions/getUserData";
import { useVersionContext } from "../../builder/version/versionContext";


const Templates = () => {
  const { templates, removeTemplate, setTemplates } = useTemplateStore();
  const { setSelectedZone, selectedZone } = useSelectedZoneStore();
  const { visualizationSocket } = useSocketStore();
  const { selectedVersionStore } = useVersionContext();
  const { selectedVersion } = selectedVersionStore();
  const { projectId } = useParams();
  const { userName, userId, organization, email } = getUserData();

  useEffect(() => {
    async function templateData() {
      try {
        let response = await getTemplateData(organization, projectId, selectedVersion?.versionId || '');
        setTemplates(response);
      } catch (error) {
        echo.error("Failed to fetching template data");
        console.error("Error fetching template data:", error);
      }
    }

    templateData();
  }, [selectedVersion?.versionId]);

  const handleDeleteTemplate = async (
    e: React.MouseEvent<HTMLButtonElement>,
    id: string
  ) => {
    try {
      e.stopPropagation();
      const { userId, organization, email } = getUserData();
      let deleteTemplate = {
        organization,
        templateID: id,
        versionId: selectedVersion?.versionId || '',
        userId, 
        projectId
      };
      if (visualizationSocket) {
        visualizationSocket.emit(
          "v1:viz-template:deleteTemplate",
          deleteTemplate
        );
      }
      removeTemplate(id);
    } catch (error) {
      echo.error("Failed to delete template");
      console.error("Error deleting template:", error);
    }
  };

  const handleLoadTemplate = async (template: any) => {
    try {
      if (selectedZone.zoneName === "") return;
      const { userId, organization, email } = getUserData();

      let loadingTemplate = {
        organization,
        zoneUuid: selectedZone.zoneUuid,
        templateID: template.id,
        versionId: selectedVersion?.versionId || '',
        projectId,
        userId
      };

      if (visualizationSocket) {
        visualizationSocket.emit("v1: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.zoneUuid);

      if (Array.isArray(template.floatingWidget)) {
        template.floatingWidget.forEach((val: any) => {
          useDroppedObjectsStore
            .getState()
            .addObject(selectedZone.zoneName, val);
        });
      }
    } catch (error) {
      echo.error("Failed to load template");
      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">
              <RenameInput value={`Template ${index + 1}`} />
            </div>
            <button
              id="template-delete-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">
          <h2>No saved templates yet.</h2>
          <div className="content">Create one in the visualization view!</div>
        </div>
      )}
    </div>
  );
};

export default Templates;
