import { BaseAuthProps } from './types';
import { AuthWrapper } from '@/components/AuthWrapper';
import { Grid, Stack, Typography } from '@mui/material';
import _ from 'lodash';
import { useAuthProvider, useNotify, useTranslate } from 'ra-core';
import { useEffect } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';

function ActivatePage({ name, copy, logo, version, background }: BaseAuthProps): JSX.Element {
  const translate = useTranslate();
  const authProvider = useAuthProvider();
  const notify = useNotify();
  const navigate = useNavigate();
  const { token } = useParams();
  useEffect(() => {
    if (typeof authProvider.activate !== 'function') {
      throw new Error('The authProvider used for the ActivatePage must define an activate() method');
    }
    authProvider
      .activate(token)
      .then(() => {
        notify('ra.auth.activate_success', { type: 'info' });
        _.delay(() => navigate('/login'), 1000);
      })
      .catch((error: any) => {
        notify(error, { type: 'error' });
        _.delay(() => navigate('/login'), 1000);
      });
  }, [token, authProvider, notify, navigate]);
  return (
    <AuthWrapper name={name} copy={copy} logo={logo} version={version} background={background}>
      <Grid container spacing={3}>
        <Grid item xs={12}>
          <Stack
            direction="row"
            justifyContent="space-between"
            alignItems="baseline"
            sx={{ mb: { xs: -0.5, sm: 0.5 } }}
          >
            <Typography variant="h3">{translate('ra.auth.activate')}</Typography>
            <Typography component={Link} to={'/login'} variant="body1" sx={{ textDecoration: 'none' }} color="primary">
              {translate('ra.auth.back_to_login')}
            </Typography>
          </Stack>
        </Grid>
        <Grid item xs={12}>
          {translate('ra.auth.activate_pending')}
        </Grid>
      </Grid>
    </AuthWrapper>
  );
}

export { ActivatePage };
export type { BaseAuthProps };
