import React, { createContext, useEffect, useState } from "react";
import shallowequal from "shallowequal";

import { useRouter } from "mazlo-ui";

import { setParams } from "../../services/Router";

export const routerStateContext = createContext({
  value: {},
  setValue: null,
});

type Props = {
  children: React.ReactNode;
};
const RouterProvider = ({ children }: Props) => {
  const router = useRouter();
  const [route, setRoute] = useState(router.route);
  const [query, setQuery] = useState(router.query);
  useEffect(() => {
    if (router.route !== route || !shallowequal(query, router.query)) {
      setRoute(router.route);
      setQuery(router.query);
    }
  }, [router.query, router.route]);
  useEffect(() => {
    if (router.route !== route || !shallowequal(query, router.query)) {
      setParams(router, { ...router.query, ...query });
    }
  }, [query, route]);
  return (
    <routerStateContext.Provider value={{ value: query, setValue: setQuery }}>
      {children}
    </routerStateContext.Provider>
  );
};

export default RouterProvider;
