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 '@/routes/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'
import { useLocalization } from '@/utils/hooks/useLocalization'
import { Helmet } from 'react-helmet'

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

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

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

  const { signUp } = useAuth()
  const { translate } = useLocalization()

  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(translate('::Abp.Account.Register.ResultMessage'))
      window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
      setError('')
    }

    setSubmitting(false)
  }

  return (
    <>
      <Helmet
        titleTemplate="%s | Erp Platform"
        title={translate('AbpAccount::' + 'Register')}
        defaultTitle="Erp Platform"
      ></Helmet>

      <div className="mb-4">
        <h3 className="mb-1">{translate('::Abp.Account.Register.Title')}</h3>
        <p>{translate('::Abp.Account.Register.Message')}</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={translate('::Abp.Account.EmailAddress')}
                  invalid={errors.email && touched.email}
                  errorMessage={errors.email}
                >
                  <Field
                    type="email"
                    autoComplete="off"
                    name="email"
                    placeholder={translate('::Abp.Account.EmailAddress')}
                    component={Input}
                  />
                </FormItem>
                <FormItem
                  label={translate('::Abp.Account.Password')}
                  invalid={errors.password && touched.password}
                  errorMessage={errors.password}
                >
                  <Field
                    autoComplete="off"
                    name="password"
                    placeholder={translate('::Abp.Account.Password')}
                    component={PasswordInput}
                  />
                </FormItem>
                <FormItem
                  label={translate('::Abp.Account.ConfirmPassword')}
                  invalid={errors.confirmPassword && touched.confirmPassword}
                  errorMessage={errors.confirmPassword}
                >
                  <Field
                    autoComplete="off"
                    name="confirmPassword"
                    placeholder={translate('::Abp.Account.ConfirmPassword')}
                    component={PasswordInput}
                  />
                </FormItem>
                <FormItem
                  label={translate('::Abp.Identity.User.UserInformation.Name')}
                  invalid={errors.name && touched.name}
                  errorMessage={errors.name}
                >
                  <Field
                    type="name"
                    autoComplete="off"
                    name="name"
                    placeholder={translate('::Abp.Identity.User.UserInformation.Name')}
                    component={Input}
                  />
                </FormItem>
                <FormItem
                  label={translate('::Abp.Identity.User.UserInformation.Surname')}
                  invalid={errors.surname && touched.surname}
                  errorMessage={errors.surname}
                >
                  <Field
                    type="surname"
                    autoComplete="off"
                    name="surname"
                    placeholder={translate('::Abp.Identity.User.UserInformation.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>{translate('::Abp.Account.Register.AlreadyHaveAnAccount')} </span>
                  <ActionLink to={signInUrl}>{translate('::Abp.Account.SignIn')}</ActionLink>
                </div>
              </FormContainer>
            </Form>
          )}
        </Formik>
      </div>
    </>
  )
}

export default Register
