import { BaseAuthProps } from './types';
import { AuthWrapper } from '@/components/AuthWrapper';
import { TextInput } from '@/components/ra-inputs';
import { Button, CircularProgress, Grid, Stack, Typography } from '@mui/material';
import { email, required, useAuthProvider, useNotify, useRedirect, useTranslate } from 'ra-core';
import { useState } from 'react';
import { Form } from 'react-admin';
import { Link } from 'react-router-dom';

function RecoverPage({ name, copy, logo, version, background }: BaseAuthProps) {
  const [loading, setLoading] = useState(false);
  const translate = useTranslate();
  const redirect = useRedirect();
  const notify = useNotify();
  const authProvider = useAuthProvider();

  function handleSubmit({ email }: any) {
    setLoading(true);
    authProvider
      .recover(email)
      .then((response: any) => {
        const message = `ra.auth.recover_${response.responseCode}`;
        const type = response.responseCode === 'ok' ? 'info' : 'error';
        // @ts-ignore
        notify(message, { type });
        redirect('/login');
      })
      .catch((error: any) => {
        notify(error?.message || error?.toString(), { type: 'error' });
      })
      .finally(() => setLoading(false));
  }
  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.recover.title')}</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}>
          <Form onSubmit={handleSubmit}>
            <Grid container>
              <Grid item xs={12} sx={{ mb: 1 }}>
                <TextInput source="email" validate={[required(), email()]} />
              </Grid>
            </Grid>
            <Grid item xs={12} sx={{ mt: 1, mb: 1 }}>
              <Typography variant="caption">{translate('ra.auth.recover.inbox_help')}</Typography>
            </Grid>
            <Grid item xs={12} sx={{ mt: 1 }}>
              <Button variant="contained" type="submit" color="primary" disabled={loading} fullWidth>
                {loading ? <CircularProgress size={19} thickness={3} /> : translate('ra.auth.recover')}
              </Button>
            </Grid>
          </Form>
        </Grid>
      </Grid>
    </AuthWrapper>
  );
}
export { RecoverPage };
