import { useEffect } from "react";
import { useDroppedObjectsStore } from "../../../../store/useDroppedObjectsStore";
import useTemplateStore from "../../../../store/useTemplateStore";
import { useSelectedZoneStore } from "../../../../store/useZoneStore";
import { getTemplateData } from "../../../../services/realTimeVisulization/zoneData/getTemplate";
import { deleteTemplateApi } from "../../../../services/realTimeVisulization/zoneData/deleteTemplate";
import { loadTempleteApi } from "../../../../services/realTimeVisulization/zoneData/loadTemplate";
import { useSocketStore } from "../../../../store/store";

const Templates = () => {
  const { templates, removeTemplate } = useTemplateStore();
  const { 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 (id: string) => {
    try {
      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);
      // let response = await deleteTemplateApi(id, organization);

      // if (response.message === "Template deleted successfully") {
      // }
    } 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,
      }
      console.log('template: ', template);
      console.log('loadingTemplate: ', loadingTemplate);

      if (visualizationSocket) {
        visualizationSocket.emit("v2:viz-template:addToZone", loadingTemplate)
      }
      // let response = await loadTempleteApi(template.id, selectedZone.zoneId, organization);

      // if (response.message === "Template placed in Zone") {
        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"
      style={{
        display: "grid",
        gridTemplateColumns: "repeat(auto-fill, minmax(180px, 1fr))",
        gap: "1rem",
        padding: "1rem",
      }}
    >
      {templates.map((template) => (
        <div
          key={template.id}
          className="template-item"
          style={{
            border: "1px solid #e0e0e0",
            borderRadius: "8px",
            padding: "1rem",
            transition: "box-shadow 0.3s ease",
          }}
        >
          {template?.snapshot && (
            <div style={{ position: "relative", paddingBottom: "56.25%" }}>
              {" "}
              {/* 16:9 aspect ratio */}
              <img
                src={template.snapshot} // Corrected from template.image to template.snapshot
                alt={`${template.name} preview`}
                style={{
                  position: "absolute",
                  width: "100%",
                  height: "100%",
                  objectFit: "contain",
                  borderRadius: "4px",
                  cursor: "pointer",
                  transition: "transform 0.3s ease",
                  // ':hover': {
                  //   transform: 'scale(1.05)'
                  // }
                }}
                onClick={() => handleLoadTemplate(template)}
              />
            </div>
          )}
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              marginTop: "0.5rem",
            }}
          >
            <div
              onClick={() => handleLoadTemplate(template)}
              style={{
                cursor: "pointer",
                fontWeight: "500",
                // ':hover': {
                //   textDecoration: 'underline'
                // }
              }}
            >
              {template.name}
            </div>
            <button
              onClick={() => handleDeleteTemplate(template.id)}
              style={{
                padding: "0.25rem 0.5rem",
                background: "#ff4444",
                color: "white",
                border: "none",
                borderRadius: "4px",
                cursor: "pointer",
                transition: "opacity 0.3s ease",
                // ':hover': {
                //   opacity: 0.8
                // }
              }}
              aria-label="Delete template"
            >
              Delete
            </button>
          </div>
        </div>
      ))}
      {templates.length === 0 && (
        <div
          style={{
            textAlign: "center",
            color: "#666",
            padding: "2rem",
            gridColumn: "1 / -1",
          }}
        >
          No saved templates yet. Create one in the visualization view!
        </div>
      )}
    </div>
  );
};

export default Templates;

