import { useMutation } from "@tanstack/react-query";
import { useContext } from "react";
import CanvasContext from "@/components/Context/canvasContext/CanvasContext";
import { fabric } from "fabric";
import useProject from "./useProject";
import { useToast } from "./use-toast";
import { deleteImage, uploadImage } from "@/api/uploadApi";

const useImageHandler = ({ removeFile }) => {
    const { toast } = useToast();

    const { canvas } = useContext(CanvasContext);

    const { projectData, projectUpdate } = useProject();

    // Upload image handler
    const { mutate: uploadMutate } = useMutation({
        mutationFn: async ({ file, id }) => await uploadImage({ file, id }),
        onSuccess: (data, { id }) => {
            if (data?.status === 200) {
                toast({ title: data?.status, description: data?.message });

                fabric.Image.fromURL(
                    data?.data[0]?.url,
                    (img) => {
                        img.applyFilters();
                        img.scale(0.5);
                        img.set("top", canvas.width / 4);
                        img.set("left", canvas.height / 4);
                        canvas.add(img);
                        canvas.setActiveObject(img);
                        // Update the active object state
                        projectUpdate({ id, updateData: { ...projectData?.data, object: canvas.toJSON(['id', 'selectable']), preview_url: "" } });
                        canvas.renderAll();
                    },
                    { crossOrigin: "anonymous" }
                );
            } else {
                toast({ variant: "destructive", title: data?.status, description: data?.message });
                removeFile();
            }
        },
    });

    // Remove image handler
    const { mutate: deleteMutate } = useMutation({
        mutationFn: async (url) => await deleteImage(url),
        onSuccess: (data, { id }) => {
            if (data?.status === 200) {
                toast({ title: data?.status, description: data?.message });

                if (canvas) {
                    projectUpdate({ id, updateData: { ...projectData?.data, object: canvas.toJSON(['id', 'selectable']) } });
                }
            } else {
                toast({ variant: "destructive", title: data?.status, description: data?.message });
            }
        },
    });

    return { uploadMutate, deleteMutate };
};

export default useImageHandler;
