import { getUserData } from "../../../functions/getUserData";
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;
  projectId?: string;
  versionId?: string
};

// 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,
  projectId,
  versionId
}: HandleSaveTemplateProps): Promise<void> => {
  try {
    const { userId, organization, email } = getUserData();
    // Check if the selected zone has any widgets
    if (!selectedZone.panelOrder || selectedZone.panelOrder.length === 0) {
      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
    if (!organization) {
      return;
    }
    let saveTemplate = {
      organization,
      template: newTemplate,
      userId,
      projectId,
      versionId
    };
    if (visualizationSocket) {
      visualizationSocket.emit("v1:viz-template:add", saveTemplate);
    }

    // Save the template
    try {
      addTemplate(newTemplate);
      // const response = await saveTemplateApi(organization, newTemplate);
      //

      // Add template only if API call succeeds
    } catch (apiError) {
      //
    }
  } catch (error) {
    echo.error("Failed to save template");
  }
};
