import { Route, Routes, Navigate, useLocation, useNavigate } from 'react-router-dom';

import { useEffect } from 'react';
import { isEmpty } from 'lodash';
import { useQuery, useQueryClient } from 'react-query';

import { ROUTES } from './constants/paths';
import { EVENT_NAMES, TIME_INTERVALS } from './constants/define';
import { AdminRoutes } from './routes';
import Layout from './layouts/Layout';
import { PrivateRoute } from './components/common';
import { NotFound, Login, ForgotPassword, ChangePassword } from './scenes';
import { useAuth } from './hooks';

const App = () => {




  // reuquest user data
  useEffect(() => {
    window.requestrememberuser['requestUserData']();
  }, []);

  const location = useLocation(),
    navigate = useNavigate(),
    { user, logout } = useAuth(),
    queryClient = useQueryClient(),
    isPublicRoute = ['/', '/login'].includes(location.pathname);

  useQuery({
    queryKey: [EVENT_NAMES.ESSENTIAL.RETRIEVE],
    queryFn: () => window.grpcAPIs[EVENT_NAMES.ESSENTIAL.RETRIEVE](),
    staleTime: TIME_INTERVALS.TEN_MINUTES_IN_MILLISECONDS,
    enabled: !isEmpty(user),
  });

  useEffect(() => {
    const navigateToResetPassword = (event, value) => {
      navigate(`${ROUTES.CHANGE_PASSWORD.path}?${value}`);
    };
    window.common[EVENT_NAMES.COMMON.NAVIGATE_CHANGE_PASSWORD_PAGE](navigateToResetPassword);

    return () => {
      window.common[EVENT_NAMES.COMMON.REMOVE_EVENT_LISTENER](
        [EVENT_NAMES.COMMON.NAVIGATE_CHANGE_PASSWORD_PAGE],
        navigateToResetPassword,
      );
    };
  }, []);

  useEffect(() => {
    if (isEmpty(user)) {
      if (!isPublicRoute) {
        logout();
      }
    } else {
      queryClient.invalidateQueries([EVENT_NAMES.ESSENTIAL.RETRIEVE]);
      if (isPublicRoute) {
        navigate(ROUTES.DASHBOARD.ROOT.path, { replace: true });
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [JSON.stringify(user)]);

  return (
    <Routes>
      <Route element={<PrivateRoute />}>
        <Route path="*" element={<AdminRoutes />} />
      </Route>
      <Route element={<Layout />}>
        <Route path={ROUTES.LOGIN.path} element={<Login />} />
        <Route path={ROUTES.FORGOT_PASSWORD.path} element={<ForgotPassword />} />
        <Route path={ROUTES.CHANGE_PASSWORD.path} element={<ChangePassword />} />
        <Route path={ROUTES.NOT_FOUND.path} element={<NotFound />} />
        <Route path="*" element={<Navigate to="/404" />} />
      </Route>
      <Route path="/" element={<Navigate to="/login" />} />
    </Routes>
  );
};

export default App;
