import { saveTemplateApi } from "../../services/realTimeVisulization/zoneData/saveTempleteApi";
import { useSocketStore } from "../../store/store";
import { Template } from "../../store/useTemplateStore";
import { captureVisualization } from "./captureVisualization";

type HandleSaveTemplateProps = {
  addTemplate: (template: Template) => void;
  floatingWidget: []; // Updated type from `[]` to `any[]` for clarity
  widgets3D: []; // Updated type from `[]` to `any[]` for clarity
  selectedZone: {
    panelOrder: string[];
    widgets: any[];
  };
  templates?: Template[];
  visualizationSocket: any;
};

// Generate a unique ID
const generateUniqueId = (): string => {
  return `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
};

export const handleSaveTemplate = async ({
  addTemplate,
  floatingWidget,
  widgets3D,
  selectedZone,
  templates = [],
  visualizationSocket,
}: HandleSaveTemplateProps): Promise<void> => {
  try {
    // Check if the selected zone has any widgets
    if (!selectedZone.panelOrder || selectedZone.panelOrder.length === 0) {
      console.warn("No widgets found in the selected zone.");
      return;
    }

    // Check if the template already exists
    const isDuplicate = templates.some(
      (template) =>
        JSON.stringify(template.panelOrder) ===
          JSON.stringify(selectedZone.panelOrder) &&
        JSON.stringify(template.widgets) ===
          JSON.stringify(selectedZone.widgets)
    );

    if (isDuplicate) {
      return;
    }

    // Capture visualization snapshot
    const snapshot = await captureVisualization();

    // if (!snapshot) {
    //   return;
    // }
    // Create a new template
    const newTemplate: Template = {
      id: generateUniqueId(),
      name: `Template ${new Date().toISOString()}`, // Better name formatting
      panelOrder: selectedZone.panelOrder,
      widgets: selectedZone.widgets,
      snapshot,
      floatingWidget,
      widgets3D,
    };

    // Extract organization from email
    const email = localStorage.getItem("email") || "";
    const organization = email.includes("@")
      ? email.split("@")[1]?.split(".")[0]
      : "";

    if (!organization) {
      console.error("Organization could not be determined from email.");
      return;
    }
    let saveTemplate = {
      organization: organization,
      template: newTemplate,
    };
    if (visualizationSocket) {
      visualizationSocket.emit("v2:viz-template:add", saveTemplate);
    }

    // Save the template
    try {
      addTemplate(newTemplate);
      // const response = await saveTemplateApi(organization, newTemplate);
      // console.log("Save API Response:", response);

      // Add template only if API call succeeds
    } catch (apiError) {
      // console.error("Error saving template to API:", apiError);
    }
  } catch (error) {
    // console.error("Error in handleSaveTemplate:", error);
  }
};
