import { create } from "zustand";
import { devtools } from "zustand/middleware";


type CropModalStore = {
    imageBlob: Blob | null;
    originalImageUrl: string | null;
};

export const initialState: CropModalStore = {
    imageBlob: null,
    originalImageUrl: null,
};

export const useCropModalStore = create<CropModalStore>()(
    devtools(
        () => initialState,
        {
            name: "CropModalStore",
            enabled: process.env.NODE_ENV === "development",
            trace: process.env.NODE_ENV === "development",
        }
    ),
);

export const setCropModal = async (
    imageBlob: Blob | string | null,
    originalImageUrl: string | null | undefined,
) => {
    if (typeof imageBlob === "string") {
        const response = await fetch(imageBlob);
        imageBlob = await response.blob();
    }

    useCropModalStore.setState({
        imageBlob,
        originalImageUrl: originalImageUrl ?? null,
    }, false, {
        type: "setCropModal",
        imageBlob,
        originalImageUrl,
    });
};

export const closeCropModal = () => useCropModalStore.setState(
    initialState,
    false,
    "closeCropModal"
);

export const setCropModalImageBlob = async (image: Blob | string | null) => {
    if (typeof image === "string") {
        const response = await fetch(image);
        image = await response.blob();
    }

    useCropModalStore.setState({
        imageBlob: image,
    }, false, {
        type: "setCropModalImageBlob",
        image,
    });
};

export const setCropModalOriginalImageUrl = (originalImageUrl: string | null | undefined) => useCropModalStore.setState(
    { originalImageUrl: originalImageUrl ?? null },
    false,
    "setCropModalOriginalImageUrl"
);
