import ActionLink from '@/components/shared/ActionLink'
import PasswordInput from '@/components/shared/PasswordInput'
import Alert from '@/components/ui/Alert'
import Button from '@/components/ui/Button'
import { FormContainer, FormItem } from '@/components/ui/Form'
import Input from '@/components/ui/Input'
import { ROUTES_ENUM } from '@/constants/route.constant'
import useAuth from '@/utils/hooks/useAuth'
import useTimeOutMessage from '@/utils/hooks/useTimeOutMessage'
import Captcha from '@/components/shared/Captcha'
import { Field, Form, Formik } from 'formik'
import { useState } from 'react'
import * as Yup from 'yup'

type SignUpFormSchema = {
  password: string
  email: string
  name: string
  surname: string
  captchaResponse: string
}

const validationSchema = Yup.object().shape({
  email: Yup.string().email('Invalid email').required('Please enter your email'),
  password: Yup.string().required('Please enter your password'),
  confirmPassword: Yup.string().oneOf([Yup.ref('password')], 'Your passwords do not match'),
  name: Yup.string().required('Name is required'),
  surname: Yup.string().required('Surname is required'),
})

const Register = () => {
  const disableSubmit = false
  const signInUrl = ROUTES_ENUM.account.login

  const { signUp } = useAuth()

  const [message, setMessage] = useState('')
  const [error, setError] = useTimeOutMessage(10000)

  const onSignUp = async (
    values: SignUpFormSchema,
    setSubmitting: (isSubmitting: boolean) => void,
  ) => {
    setSubmitting(true)
    const result = await signUp(values)

    if (result?.status === 'failed') {
      setError(result.message)
      setMessage('')
    } else {
      setMessage('Success. Please confirm your account by clicking the link.')
      window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
      setError('')
    }

    setSubmitting(false)
  }

  return (
    <>
      <div className="mb-8">
        <h3 className="mb-1">Sign Up</h3>
        <p>And lets get started with your free trial</p>
      </div>
      <div>
        {message && (
          <Alert showIcon className="mb-4" type="success">
            {message}
          </Alert>
        )}
        {error && (
          <Alert showIcon className="mb-4" type="danger">
            {error}
          </Alert>
        )}
        <Formik
          initialValues={{
            email: '',
            password: '',
            confirmPassword: '',
            name: '',
            surname: '',
            captchaResponse: '',
          }}
          validationSchema={validationSchema}
          onSubmit={(values, { setSubmitting }) => {
            if (!disableSubmit) {
              onSignUp(values, setSubmitting)
            } else {
              setSubmitting(false)
            }
          }}
        >
          {({ touched, errors, isSubmitting, setFieldValue }) => (
            <Form>
              <FormContainer>
                <FormItem
                  label="Email"
                  invalid={errors.email && touched.email}
                  errorMessage={errors.email}
                >
                  <Field
                    type="email"
                    autoComplete="off"
                    name="email"
                    placeholder="Email"
                    component={Input}
                  />
                </FormItem>
                <FormItem
                  label="Password"
                  invalid={errors.password && touched.password}
                  errorMessage={errors.password}
                >
                  <Field
                    autoComplete="off"
                    name="password"
                    placeholder="Password"
                    component={PasswordInput}
                  />
                </FormItem>
                <FormItem
                  label="Confirm Password"
                  invalid={errors.confirmPassword && touched.confirmPassword}
                  errorMessage={errors.confirmPassword}
                >
                  <Field
                    autoComplete="off"
                    name="confirmPassword"
                    placeholder="Confirm Password"
                    component={PasswordInput}
                  />
                </FormItem>
                <FormItem
                  label="Name"
                  invalid={errors.name && touched.name}
                  errorMessage={errors.name}
                >
                  <Field
                    type="name"
                    autoComplete="off"
                    name="name"
                    placeholder="Name"
                    component={Input}
                  />
                </FormItem>
                <FormItem
                  label="Surname"
                  invalid={errors.surname && touched.surname}
                  errorMessage={errors.surname}
                >
                  <Field
                    type="surname"
                    autoComplete="off"
                    name="surname"
                    placeholder="Surname"
                    component={Input}
                  />
                </FormItem>
                <Captcha
                  onError={() => setFieldValue('captchaResponse', '')}
                  onExpire={() => setFieldValue('captchaResponse', '')}
                  onSuccess={(token) => setFieldValue('captchaResponse', token)}
                />
                <Button block loading={isSubmitting} variant="solid" type="submit">
                  {isSubmitting ? 'Creating Account...' : 'Sign Up'}
                </Button>
                <div className="mt-4 text-center">
                  <span>Already have an account? </span>
                  <ActionLink to={signInUrl}>Sign in</ActionLink>
                </div>
              </FormContainer>
            </Form>
          )}
        </Formik>
      </div>
    </>
  )
}

export default Register
