import { useLocation, useMatch, useNavigate } from 'react-router-dom';

import useIds from './useIds';
import useRoutes from './useRoutes';

const useNavigateBack = () => {
  const routes = useRoutes();
  const navigate = useNavigate();
  const location = useLocation();
  const { pathId, courseId } = useIds();

  const { backRoute } = (location.state ?? {}) as { backRoute?: string };

  const isCourseDetail = !!useMatch(routes.courses.detail(courseId!));
  const isPathDetail = !!useMatch(routes.paths.detail(pathId!));

  const getBackRoute = () => {
    if (backRoute) return backRoute;

    if (pathId) {
      if (isPathDetail) return routes.paths.list();
      if (isCourseDetail) return routes.paths.detail(pathId);
      if (courseId) return routes.courses.detail(courseId);
      return routes.paths.detail(pathId);
    }

    if (courseId) {
      if (isCourseDetail) return routes.courses.list();
      return routes.courses.detail(courseId!);
    }

    return '/';
  };

  return () => navigate(getBackRoute());
};

export default useNavigateBack;
