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 RegisterPage({ name, copy, version, logo, background }: BaseAuthProps) {
  const [loading, setLoading] = useState(false);
  const translate = useTranslate();
  const redirect = useRedirect();
  const notify = useNotify();
  const authProvider = useAuthProvider();

  function handleSubmit(values: any) {
    setLoading(true);
    authProvider
      .register(values)
      .then((response: any) => {
        const message = `ra.auth.register_${response.responseCode}`;
        const type = response.responseCode === 'ok' ? 'info' : 'error';
        // @ts-ignore
        notify(message, { type });
        redirect('/login');
      })
      .catch((error: any) => {
        notify(error.message || error, { type: 'error' });
      })
      .finally(() => setLoading(false));
  }
  return (
    <AuthWrapper name={name} copy={copy} logo={logo} background={background} version={version}>
      <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.register.title')}</Typography>
            <Typography component={Link} to={'/login'} variant="body1" sx={{ textDecoration: 'none' }} color="primary">
              {translate('ra.auth.already_have_account')}
            </Typography>
          </Stack>
        </Grid>
        <Grid item xs={12}>
          <Form onSubmit={handleSubmit}>
            <Grid container>
              <Grid item xs={12} sx={{ mb: 1 }}>
                <TextInput source="name" label={translate('ra.register.name')} validate={required()} />
              </Grid>
              <Grid item xs={12} sx={{ mb: 1 }}>
                <TextInput source="email" type="email" validate={[required(), email()]} />
              </Grid>
              <Grid item xs={12} sx={{ mb: 1 }}>
                <TextInput source="password" type="password" validate={required()} />
              </Grid>
            </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.create_account')}
              </Button>
            </Grid>
          </Form>
        </Grid>
      </Grid>
    </AuthWrapper>
  );
}

export { RegisterPage };
