import type { PropsWithChildren } from "react";
import { useCallback, useState } from "react";

import { BlanketContext } from "./BlanketContext";

export function BlanketProvider({
  children,
  color,
  zIndex,
}: PropsWithChildren<{
  zIndex?: number;
  color?: string;
}>) {
  const [isOpen, setIsOpen] = useState<boolean>(false);
  const [top, setTop] = useState(0);

  const handleSetIsOpen = useCallback(
    (yesno?: boolean) => {
      if (typeof window === "undefined") return;

      if (yesno) {
        const scrollTop = window.scrollY;
        document.body.style.top = `-${scrollTop}px`;
        setTop(scrollTop);
      }

      if (window.innerHeight < document.body.scrollHeight) {
        document.body.style.overflowY = (!!yesno && "scroll") || "auto";
        document.body.style.position = (!!yesno && "fixed") || "static";
      }

      window.scrollTo({ top });
      setIsOpen(() => !!yesno);
    },
    [top]
  );

  return (
    <BlanketContext.Provider
      value={{
        isOpen,
        setIsOpen: handleSetIsOpen,
        color: color || `rgba(0,0,0,0.5)`,
        zIndex: zIndex || 200,
      }}
    >
      {children}
    </BlanketContext.Provider>
  );
}