import { Button, Flex, Typography, Box } from '@tidbcloud/uikit'
import { Form, FormActions, FormErrorMessage, FormTextInput } from '@tidbcloud/uikit/biz'
import { IconCheckCircle } from '@tidbcloud/uikit/icons'
import React, { useState, useEffect } from 'react'

import Link from 'dbaas/components/Link'
import auth, { databaseConnection } from 'dbaas/services/auth'
import { emailRegEx } from 'dbaas/utils/regex'
import { eventTracking } from 'dbaas/utils/tracking'
import { useGAPageView } from 'dbaas/utils/tracking/usePageViewTracking'
import { useCountingDown } from 'dbaas/utils/useCountingDown'

type FormValues = { email: string }

const ForgotPassword: React.FC<
  React.PropsWithChildren<{
    title?: string
    reason?: string
  }>
> = ({ title = 'Forgot Password', reason = '' }) => {
  const params = new URLSearchParams(window.location.search)
  const isPending = params.get('type') === 'pending'
  const [email, setEmail] = useState(isPending ? localStorage.getItem('sign_in_email') || '' : '')
  const [sending, setSending] = useState(false)
  const { counter } = useCountingDown(sending)
  const [error, setError] = useState('')
  const [step, setStep] = useState(1)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (counter === 0) {
      setSending(false)
    }
  }, [counter])

  const login = (e: React.MouseEvent<HTMLAnchorElement | HTMLButtonElement>) => {
    e.preventDefault()
    auth.login()
  }

  const handleSubmit = async (data: FormValues) => {
    if (loading) {
      return
    }
    setLoading(true)
    auth.auth0.changePassword(
      {
        connection: databaseConnection,
        email: data.email
      },
      function (err, result) {
        setError(err ? err.description || 'Unknown error.' : '')
        setLoading(false)

        if (result) {
          setEmail(data.email)
          setSending(true)
          setStep(2)
        }
      }
    )
  }

  const handleResend = async () => {
    if (loading) {
      return
    }
    setLoading(true)
    auth.auth0.changePassword(
      {
        connection: databaseConnection,
        email
      },
      function (err, result) {
        setLoading(false)
        if (result) {
          setSending(true)
        } else {
          console.error(err?.description || 'Unknown error.')
        }
      }
    )
    eventTracking('Forget Password Resend Button Clicked"')
  }

  useGAPageView()

  useEffect(() => {
    if (isPending && !auth.isAuthenticated()) {
      return auth.authorizeWithPrev()
    }
  }, [isPending])

  return (
    <Flex direction="column" h="100vh" bg="carbon.2">
      <Flex sx={{ flex: 1 }} direction="column" align="center" pt={56}>
        {email && step === 2 ? (
          <Flex w={532} direction="column" align="center">
            <IconCheckCircle size={64} c="green.6" />
            <Box mt={16}>
              <Typography variant="body-lg" ta="center">
                An email has just been sent to <strong>{email}</strong>.
              </Typography>
              {isPending ? (
                <Flex direction="column" align="center">
                  <Typography>Please check your email inbox and follow two steps to complete the process.</Typography>
                  <Box ta="left">
                    <Typography mb={8}>Step 1: Set your password via the first email.</Typography>
                    <Typography>Step 2: Activate your signup account via the second email.</Typography>
                  </Box>
                </Flex>
              ) : (
                <Typography ta="center" variant="body-lg" mt={16}>
                  Please check your email inbox and follow the instructions to complete the process.
                </Typography>
              )}
            </Box>
            <Box ta="center" mt={16}>
              <Typography variant="body-lg">Didn't receive an email?</Typography>
              <Button
                disabled={sending}
                onClick={handleResend}
                loading={loading}
                data-mp-event="mp--1691461012505"
                mt={16}
              >
                {sending ? `You can try to resend the verification email after ${counter}s` : 'Resend'}
              </Button>
            </Box>
          </Flex>
        ) : (
          <Flex w={532} direction="column" align="center">
            <Typography ta="center" variant="headline-lg" fz={28}>
              {title}
            </Typography>
            <Box mt={16}>
              {reason && (
                <Typography variant="body-lg" ta="center">
                  {reason}
                </Typography>
              )}
              {isPending ? (
                <Box ta="left">
                  <Typography variant="body-lg">
                    Finding you have a same signup account with your SSO email, It is pending. If you forget the
                    password, you need to set a new password and then activate your signup accounts.
                  </Typography>
                  <Box ta="left" my={8}>
                    <Typography mb={8} variant="body-lg">
                      Step 1: Click the "Send" Button, send an Email to set a new password.
                    </Typography>
                    <Typography variant="body-lg">
                      Step 2: After setting password, you will receive another Email to activate your signup account.
                    </Typography>
                  </Box>
                </Box>
              ) : (
                <Typography variant="body-lg" ta="center">
                  Enter your TiDB Cloud email address that you used to register. We'll send you an email with a link to
                  reset your password.
                </Typography>
              )}
            </Box>

            <Form<FormValues>
              defaultValues={{ email: isPending ? email : '' }}
              onSubmit={handleSubmit}
              withActions={false}
              mt={16}
              w={336}
            >
              <FormTextInput
                name="email"
                placeholder="Email"
                readOnly={isPending}
                rules={{
                  required: 'Required',
                  pattern: {
                    value: emailRegEx,
                    message: 'Invalid email address'
                  }
                }}
              />
              <FormActions
                mt={8}
                cancelProps={{ display: 'none' }}
                justify="center"
                loading={loading}
                confirmProps={{
                  'data-mp-event': 'mp-send-1691461012508'
                }}
                confirmText="Send"
              />
              {error && <FormErrorMessage message={error} />}
            </Form>
          </Flex>
        )}
      </Flex>
      <Flex direction="column" align="center" justify="center" py={24}>
        <Typography variant="body-lg">
          Already have an account?{' '}
          <Link onClick={login} href="/" eventName="Sign In Link Clicked" eventParams={{ source: 'Forget Password' }}>
            Sign In
          </Link>
        </Typography>
        <Typography variant="body-lg" mt={16}>
          If you have any question, please visit{' '}
          <Link
            href="https://support.pingcap.com/hc/en-us/"
            target="_blank"
            rel="noopener noreferrer"
            eventName="Support Pingcap Link Clicked"
            eventParams={{ source: 'Forget Password' }}
          >
            support.pingcap.com
          </Link>{' '}
          for help.
          <br />
        </Typography>
      </Flex>
    </Flex>
  )
}

export default ForgotPassword
