import { useEffect, useState } from 'react';
import { useTheme } from '@mui/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useRightSideBar } from '../right-sidebar';
import type { DrawerStates } from '../sidebar';
import { LayoutProps } from './types';

/**
 * Defines layout behavior.
 * @param disableSizeChanges
 * @param initLeftState
 * @returns
 */
export const useLayoutBehavior = (
  disableSizeChanges?: LayoutProps['disableSizeChanges'],
  initLeftState?: LayoutProps['initLeftState']
) => {
  const theme = useTheme();
  const { setOpen, setDrawerLocked, open: isRightSidebarOpen, defaultMod } = useRightSideBar();

  const [leftDrawerOpenState, setLeftDrawerOpenState] = useState<DrawerStates>(
    initLeftState || 'closed'
  );
  const MIN_WIDTH_TO_OPEN_LEFT = 1616;
  const isMdUp = useMediaQuery(theme.breakpoints.up(MIN_WIDTH_TO_OPEN_LEFT));
  const isSmUp = useMediaQuery(theme.breakpoints.up('customsm'));

  const handleDrawerChange = () => {
    if (disableSizeChanges) return;
    if (!defaultMod) return;
    if (!isSmUp && !isMdUp && leftDrawerOpenState === 'locked') {
      return;
    }
    if (!isMdUp && leftDrawerOpenState === 'locked') {
      setOpen(false);
      setDrawerLocked(false);
    } else if (!isMdUp && isRightSidebarOpen) {
      setLeftDrawerOpenState('closed');
    }
  };

  useEffect(() => {
    if (disableSizeChanges) {
      return setLeftDrawerOpenState(initLeftState || 'closed');
    }
  }, [disableSizeChanges, initLeftState]);

  useEffect(() => {
    if (disableSizeChanges) return;
    if (!isSmUp) {
      setLeftDrawerOpenState('closed');
    } else {
      setLeftDrawerOpenState(
        (localStorage.getItem('navigationMenuState') || 'locked') as DrawerStates
      );
    }
  }, [disableSizeChanges, isSmUp]);

  return {
    leftDrawerOpenState,
    setLeftDrawerOpenState,
    handleDrawerChange
  };
};
