import { Box, Card, Flex, Typography, CardProps } from '@tidbcloud/uikit'
import { Form, FormTextInput } from '@tidbcloud/uikit/biz'
import { Suspense } from 'react'
import { Link } from 'react-router-dom'

import auth, { AUTH_CALLBACK_URI, databaseConnection } from 'dbaas/services/auth'
import { useGAPageView } from 'dbaas/utils/tracking/usePageViewTracking'

import { useIsMdScreen } from '../Components/helpers'
import { PageShell } from '../Components/Shell'
import { SSOLogin } from '../Components/SSO'

export const SignIn = () => {
  const isMd = useIsMdScreen()

  const cardProps: Omit<CardProps, 'children'> = isMd
    ? {
        p: 0,
        w: 360,
        withBorder: false,
        shadow: 'none'
      }
    : {
        p: 24,
        w: 440
      }

  const onSubmit = async (data: { email: string; password: string }) => {
    return new Promise<any>((_resolve, reject) => {
      return auth.auth0.login(
        {
          realm: databaseConnection,
          email: data.email,
          password: data.password,
          redirectUri: `${AUTH_CALLBACK_URI}${window.location.search}`
        },
        function (err) {
          const errMsg = err?.description || ''
          reject(new Error(errMsg))
        }
      )
    })
  }

  useGAPageView()

  return (
    <Suspense fallback={<div />}>
      <PageShell>
        <Card {...cardProps}>
          <Flex justify="space-between" align="baseline" mb={16}>
            <Typography variant="headline-lg">Sign In</Typography>
            <Typography variant="label-lg" c="carbon.7">
              Don't have an account?{' '}
              <Box
                component={Link}
                to={`/oauth/signup${window.location.search}`}
                sx={{ ':hover': { textDecoration: 'none' } }}
              >
                Sign Up
              </Box>
            </Typography>
          </Flex>
          <SSOLogin action="sign-in" />
          <Form
            defaultValues={{
              email: '',
              password: ''
            }}
            onSubmit={onSubmit}
            actionsProps={{
              cancelProps: { display: 'none' },
              confirmText: 'Sign In',
              confirmProps: { w: '100%' }
            }}
          >
            <FormTextInput name="email" placeholder="Work Email" rules={{ required: 'Required' }} />
            <FormTextInput
              type="password"
              autoComplete="current-password"
              name="password"
              placeholder="Password"
              rules={{
                required: 'Required ',
                minLength: {
                  value: 8,
                  message: 'At least 8 characters in length.'
                },
                maxLength: {
                  value: 64,
                  message: 'Maximum 64 characters in length.'
                },
                pattern: {
                  value: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,64}$/,
                  message:
                    'The password should contain the following types of characters: upper case letters (A-Z), lower case letters (a-z), numbers (such as 0-9).'
                }
              }}
            />
          </Form>
          <Flex justify="space-between" mt={16}>
            <Box component={Link} to="/forgot_password" sx={{ ':hover': { textDecoration: 'none' } }}>
              Forgot password
            </Box>
            <Box
              component="a"
              rel="noreferrer"
              href="https://www.pingcap.com/contact-us/"
              sx={{ ':hover': { textDecoration: 'none' } }}
            >
              Contact us
            </Box>
          </Flex>
        </Card>
      </PageShell>
    </Suspense>
  )
}

export default SignIn
