'use client';
import { usePathname } from 'next/navigation';
import { ReactNode, createContext, useCallback, useContext, useEffect, useState } from 'react';

const FullWindowComponentContext = createContext<{
  component: null | ReactNode;
  handleToggleComponent: (component: ReactNode) => void;
} | null>(null);

export const useFullWindowContext = () => {
  const fullWindowContext = useContext(FullWindowComponentContext);
  if (!fullWindowContext) {
    throw new Error(`ERROR: User reached logged-in-only component with null 'user' in context`);
  }
  return fullWindowContext;
};

export default function FullWindowComponentContextProvider({ children }: { children: ReactNode }) {
  const [component, setComponent] = useState<null | ReactNode>(null);
  const pathname = usePathname();

  const handleToggleComponent = useCallback(
    (openingComponent: ReactNode) => {
      if (component) {
        return setComponent(null);
      }
      return setComponent(openingComponent);
    },
    [component],
  );

  useEffect(() => {
    if (component) {
      setComponent(null);
    }
  }, [pathname]);

  return (
    <FullWindowComponentContext.Provider value={{ component, handleToggleComponent }}>
      {component ? (
        <div className='full_screen mt-8 w-full h-[75vh] flex justify-center items-center'>
          {component}
        </div>
      ) : (
        children
      )}
    </FullWindowComponentContext.Provider>
  );
}
