// ** Demo Components Imports
import { Stack, Typography } from '@mui/material';

import { setup } from 'src/lib/csrf';

import { useEffect } from 'react';
import { useRouter } from 'next/router';
import CheckSession from 'src/api/checkSession';

const Dashboard = () => {
  const route = useRouter();

  useEffect(() => {
    const check = async () => {
      try {
        let { session } = JSON.parse(localStorage.getItem('session')) || '';

        // fetch(`/api/auth/check_session?session=${session}`)
        //   .then(res => res.json())
        //   .then(res_json => {
        //     let { status } = res_json;

        //     if (status != 'OK') {
        //       localStorage.clear('session');
        //       router.replace('/admin/login');
        //     }
        //   })
        //   .catch(error => {
        //     console.error(error);
        //   });

        let data = await CheckSession({ session });
        if (data['status'] != 'OK') {
          return route.replace('/admin/login');
        } else {
          // assume 'status' is ok here
          if (data['role'] == 'admin') {
            return route.replace('/admin');
          } else {
            return route.replace('/shopfront/customer/profile');
          }
        }
      } catch (error) {}
    };

    return check();
  }, []);

  return (
    <Stack direction="row" justifyContent={'center'} alignItems={'center'} minHeight={'60vh'}>
      <Typography variant="h5">hello admin !</Typography>
    </Stack>
  );
};

export default Dashboard;

export const getServerSideProps = setup(async ({ req, res }) => {
  return { props: {} };
});
