import { useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { View } from "@/app/deals/components/desktop/TopToolPanel/TopToolPanel";

const useView = () => {
    const router = useRouter();
    const searchParams = useSearchParams();
    const viewsArray = Object.values(View);

    const [view, setView] = useState<View>(() => {
        const urlView = searchParams.get("view") as View;
        return urlView && viewsArray.includes(urlView) ? urlView : View.BOARD;
    });

    useEffect(() => {
        const urlView = searchParams.get("view") as View;
        if (urlView && viewsArray.includes(urlView)) {
            setView(urlView);
        }
    }, [searchParams]);

    useEffect(() => {
        const params = new URLSearchParams(searchParams.toString());
        if (params.get("view") === view) return;
        router.replace(`?view=${view}`);
    }, [view]);

    return {
        view,
        setView,
    };
};

export default useView;
