import axiosInstance from '@/plugins/axios-plugin';
import { mountStoreDevtool } from 'simple-zustand-devtools';
import { toast } from 'sonner';
import { route } from 'ziggy-js';
import { create } from 'zustand';
import { devtools } from 'zustand/middleware';

const useMediaStore = create(
    devtools((set, get) => ({
        currentTab: 'memes',

        memes: [],
        backgrounds: [],
        isFetchingMemes: false,
        isFetchingBackgrounds: false,

        // Selected items
        selectedMeme: null,
        selectedBackground: null,
        currentCaption: 'I am chicken rice',
        watermarked: true,

        setCurrentTab: (tab) => {
            set({ currentTab: tab });
        },

        // Selection actions
        selectMeme: (meme) => {
            set({ selectedMeme: meme });
        },

        selectBackground: (background) => {
            set({ selectedBackground: background });
        },

        // Clear selections
        clearSelectedMeme: () => {
            set({ selectedMeme: null });
        },

        clearSelectedBackground: () => {
            set({ selectedBackground: null });
        },

        init: async () => {
            try {
                const response = await axiosInstance.post(route('api.app.init'));

                if (response?.data?.success?.data?.init) {
                    set({
                        currentCaption: response.data.success.data.init.caption,
                        selectedMeme: response.data.success.data.init.meme,
                        selectedBackground: response.data.success.data.init.background,
                    });
                } else {
                    throw 'Invalid API response';
                }
            } catch (error) {
                console.error('Error fetching init:', error);

                throw error;
            }
        },

        // Fetch memes (overlays)
        fetchMemes: async () => {
            set({ isFetchingMemes: true });
            try {
                const response = await axiosInstance.post(route('api.app.memes'));

                if (response?.data?.success?.data?.memes) {
                    set({
                        memes: response.data.success.data.memes,
                        isFetchingMemes: false,
                    });
                    return response.data.success.data.memes;
                } else {
                    throw 'Invalid API response';
                }
            } catch (error) {
                console.error('Error fetching memes:', error);
                set({ isFetchingMemes: false });
                if (error?.response?.data?.error?.message?.length > 0) {
                    toast.error(error.response.data.error.message);
                }
                throw error;
            }
        },

        // Fetch backgrounds
        fetchBackgrounds: async () => {
            set({ isFetchingBackgrounds: true });
            try {
                const response = await axiosInstance.post(route('api.app.background'));

                if (response?.data?.success?.data?.backgrounds) {
                    set({
                        backgrounds: response.data.success.data.backgrounds,
                        isFetchingBackgrounds: false,
                    });
                    return response.data.success.data.backgrounds;
                } else {
                    throw 'Invalid API response';
                }
            } catch (error) {
                console.error('Error fetching backgrounds:', error);
                set({ isFetchingBackgrounds: false });
                if (error?.response?.data?.error?.message?.length > 0) {
                    toast.error(error.response.data.error.message);
                }
                throw error;
            }
        },

        // Reset store to default state
        restoreMemeStateToDefault: () => {
            console.log('restoreMemeStateToDefault');
            set({
                memes: [],
                backgrounds: [],
                isFetchingMemes: false,
                isFetchingBackgrounds: false,
                selectedMeme: null,
                selectedBackground: null,
            });
        },
    })),
    {
        name: 'MemeStore',
        store: 'MemeStore',
    },
);

if (import.meta.env.APP_ENV === 'local') {
    mountStoreDevtool('MediaStore', useMediaStore);
}

export default useMediaStore;
