import { useEffect } from 'react';
import { useOutletContext } from 'react-router';
import { FooterItemActiveKey } from '@/entities/common/model/types';
import { HeaderType } from '@/entities/common/model/types';
import { ContextType } from '.';

export const useSubLayoutContext = () => {
  return useOutletContext<ContextType>();
};

export const useSetOnBack = (fn: any) => {
  const { setOnBack } = useSubLayoutContext();
  useEffect(() => {
    setOnBack(() => fn);
    return () => {
      setOnBack(() => undefined);
    };
  }, [setOnBack]);
  return { setOnBack };
};

export const useSetHeaderTitle = (title: string) => {
  const { setHeaderTitle } = useSubLayoutContext();
  useEffect(() => {
    setHeaderTitle(title);
    return () => setHeaderTitle('');
  }, [title, setHeaderTitle]);
  return { setHeaderTitle };
};

export const useSetIsPullToRefreshEnabled = (enabled: boolean) => {
  const { setIsPullToRefreshEnabled } = useSubLayoutContext();
  useEffect(() => {
    setIsPullToRefreshEnabled(enabled);
    return () => setIsPullToRefreshEnabled(false);
  }, [enabled, setIsPullToRefreshEnabled]);
  return { setIsPullToRefreshEnabled };
};

export const useSetMenuOn = (menuOn: boolean) => {
  const { setMenuOn } = useSubLayoutContext();
  useEffect(() => {
    setMenuOn(menuOn);
    return () => setMenuOn(false);
  }, [menuOn, setMenuOn]);
  return { setMenuOn };
};

export const useSetHeaderType = (headerType: HeaderType) => {
  const { setHeaderType } = useSubLayoutContext();
  useEffect(() => {
    setHeaderType(headerType);
    return () => setHeaderType(HeaderType.NoHeader);
  }, [headerType, setHeaderType]);
  return { setHeaderType };
};

export const useSetFavoriteEdit = (favoriteEdit: boolean) => {
  const { setFavoriteEdit } = useSubLayoutContext();
  useEffect(() => {
    setFavoriteEdit(favoriteEdit);
    return () => setFavoriteEdit(false);
  }, [favoriteEdit, setFavoriteEdit]);
  return { setFavoriteEdit }
};

export const useSetFooterMode = (footerMode: boolean) => {
  const { setFooterMode } = useSubLayoutContext();
  useEffect(() => {
    setFooterMode(footerMode);
    return () => setFooterMode(false);
  }, [footerMode, setFooterMode]);
  return { setFooterMode };
};

export const useSetFooterCurrentPage = (footerCurrentPage?: FooterItemActiveKey | null) => {
  const { setFooterCurrentPage } = useSubLayoutContext();
  useEffect(() => {
    setFooterCurrentPage(footerCurrentPage);
    return () => setFooterCurrentPage(undefined);
  }, [footerCurrentPage, setFooterCurrentPage]);
  return { setFooterCurrentPage };
};