import { BaseAuthProps } from './types';
import { AuthBackground } from '@/components/AuthBackground';
import { AuthWrapper } from '@/components/AuthWrapper';
import { TextInput } from '@/components/ra-inputs';
import { Button, CircularProgress, Divider, Grid, Link, Stack, Typography } from '@mui/material';
import { Form, required, useCheckAuth, useLogin, useNotify, useSafeSetState, useTranslate } from 'ra-core';
import { useEffect } from 'react';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import _ from 'lodash';
import { GoogleLoginButton } from '@/components/ra-buttons';

type LoginPageProps = BaseAuthProps & {
  /**
   * Indicates whether to enable the password recovery screen.
   * If enabled, it is advisable to register a route to /recover with a component
   * that takes care of recovery, you can use the Applica component directly for this
   *
   * @see RecoverPage for more information.
   * @example
   * import { RecoverPage } from "@applica-software-guru/react-admin";
   * <CustomRoutes noLayout>
   *  <Route path="/recover" component={RecoverPage} />
   * </CustomRoutes>
   */
  enablePasswordRecover?: boolean;
  /**
   * Indicates whether to enable the registration screen.
   * If enabled, it is advisable to register a route to /register with a component
   * that takes care of registration, you can use the Applica component directly for this
   *
   * @see RegisterPage for more information.
   * @example
   * import { RegisterPage } from "@applica-software-guru/react-admin";
   * <CustomRoutes noLayout>
   *  <Route path="/register" component={RegisterPage} />
   * </CustomRoutes>
   */
  enableRegistration?: boolean;
  /**
   * Indicates the page to redirect the user to after login.
   * If not specified, the react-admin home page is used.
   */
  redirectTo: string;
  /**
   * Indicates which OAuth providers to enable and configurations.
   */
  oauth?: {
    google?: {
      clientId: string;
    };
  };
};
function LoginPage({
  version,
  name,
  copy,
  logo,
  enablePasswordRecover = false,
  enableRegistration = false,
  oauth = {},
  redirectTo,
  background = <AuthBackground />
}: LoginPageProps): JSX.Element {
  const [loading, setLoading] = useSafeSetState(false);
  const login = useLogin();
  const translate = useTranslate();
  const notify = useNotify();
  const checkAuth = useCheckAuth();
  const navigate = useNavigate();

  useEffect(() => {
    checkAuth({}, false)
      .then(() => {
        navigate('/');
      })
      .catch(() => {
        // not authenticated, stay on the login page
      });
  }, [checkAuth, navigate]);

  function handleSubmit(values: any) {
    setLoading(true);
    login(values, redirectTo)
      .then(() => {
        setLoading(false);
      })
      .catch((error) => {
        setLoading(false);
        notify(
          typeof error === 'string'
            ? error
            : typeof error === 'undefined' || !error.message
            ? 'ra.auth.sign_in_error'
            : error.message,
          {
            type: 'error',
            messageArgs: {
              _: typeof error === 'string' ? error : error && error.message ? error.message : undefined
            }
          }
        );
      });
  }

  return (
    <AuthWrapper name={name} version={version} copy={copy} logo={logo} 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">Login</Typography>
            {enableRegistration ? (
              <Typography
                component={RouterLink}
                to={'/register'}
                variant="body1"
                sx={{ textDecoration: 'none' }}
                color="primary"
              >
                {translate('ra.auth.register')}
              </Typography>
            ) : null}
          </Stack>
        </Grid>
        <Grid item xs={12}>
          <Form onSubmit={handleSubmit}>
            <Grid container>
              <Grid item xs={12} sx={{ mb: 2 }}>
                <TextInput
                  autoFocus
                  source="username"
                  label={translate('ra.auth.username')}
                  autoComplete="username"
                  validate={required()}
                  placeholder="user@company.name"
                  fullWidth
                />
              </Grid>
              <Grid item xs={12} sx={{ mb: 2 }}>
                <TextInput
                  source="password"
                  label={translate('ra.auth.password')}
                  type="password"
                  autoComplete="current-password"
                  validate={required()}
                  placeholder={translate('ra.auth.password_placeholder')}
                  fullWidth
                />
              </Grid>
            </Grid>
            {enablePasswordRecover ? (
              <Grid item xs={12} sx={{ mt: 1 }}>
                <Stack direction="row" justifyContent="flex-end" alignItems="flex-end" spacing={2}>
                  <Link variant="h6" component={RouterLink} to={'/recover'} color="text.primary">
                    {translate('ra.auth.forgot_password')}
                  </Link>
                </Stack>
              </Grid>
            ) : null}
            <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.sign_in')}
              </Button>
            </Grid>
          </Form>
          {!_.isEmpty(oauth) ? (
            <>
              <Grid item xs={12} sx={{ mt: 2 }}>
                <Divider />
              </Grid>
              {oauth.google ? (
                <Grid item xs={12} sx={{ mt: 2, width: '100%' }}>
                  <GoogleLoginButton setLoading={setLoading} />
                </Grid>
              ) : null}
            </>
          ) : null}
        </Grid>
      </Grid>
    </AuthWrapper>
  );
}

export { LoginPage };
export type { LoginPageProps };
