import React, { useCallback } from "react";
import { useDispatch } from "react-redux";

import Gallery from "@/components/administrator/Gallery/gallery";

import useGalleryManagement from "../../../../hooks/useGalleryManagement";
import {
  addMiniWindow,
  removeAllMiniWindow,
} from "@/utils/store/features/ui/miniwindow.slice";
import axios from "axios";

export const useEditorPlugin = () => {
  const dispatch = useDispatch();
  const { gallery } = useGalleryManagement();

  const galleryPlugin = useCallback(async (callback) => {
    await gallery({
      page: 1,
      limit: 50,
      onSuccess: (galleries) => {
        dispatch(
          addMiniWindow({
            status: true,
            component: Gallery,
            initialData: { ...galleries, mini: true },
            onSelected: (result) => {
              try {
                callback({
                  url: result.url,
                  caption: result.alt,
                });
              } catch (error) {
              } finally {
                dispatch(removeAllMiniWindow());
              }
            },
          })
        );
      },
    });
  }, []);

  const uploadPlugin = useCallback(async (file, callback) => {
    try {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("title", file.name.split(".").slice(0, -1).join("."));
      formData.append("filename", file.name);

      const response = await axios.post("/api/upload", formData);
      callback({
        success: 1,
        file: {
          url: response.data?.files?.[0]?._url,
        },
      });
    } catch (error) {
      callback({
        success: 0,
        error: "Failed to upload image",
      });
    }
  }, []);

  return { galleryPlugin, uploadPlugin };
};
