import { yupResolver } from '@hookform/resolvers/yup';
import _ from '@lodash';
import Button from '@mui/material/Button';
import Paper from '@mui/material/Paper';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import { forwardRef } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { withTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { authService } from 'src/app/services';
import * as yup from 'yup';
import LeftSideCanvas from '../shared-components/LeftSideCanvas';

const defaultValues = {
  name: '',
  email: '',
  password: '',
  passwordConfirm: '',
};

const StyledTextField = forwardRef((props, ref) => (
  <TextField
    InputProps={{
      sx: {
        background: (theme) => theme.palette.background.paper,
        borderRadius: '10px',
      },
    }}
    {...props}
    ref={ref}
  />
));

function SignUpPage({ t }) {
  const schema = yup.object().shape({
    name: yup.string().required(t('name_error')),
    email: yup.string().email(t('email_error')).required(t('email_error')),
    password: yup.string().required(t('password_error')).min(8, t('password_error')),
    passwordConfirm: yup.string().oneOf([yup.ref('password'), null], t('password_confirm_error')),
  });

  const { control, formState, handleSubmit, setError } = useForm({
    mode: 'onChange',
    defaultValues,
    resolver: yupResolver(schema),
  });

  const { isValid, dirtyFields, errors } = formState;

  function onSubmit({ name, password, email }) {
    authService
      .createUser({
        displayName: name,
        password,
        email,
      })
      .catch((error) => {
        setError('root', {
          type: 'manual',
          message: error.message,
        });
      });
  }

  return (
    <div className="h-full flex flex-col sm:flex-row items-center md:items-start sm:justify-center md:justify-start flex-auto min-w-0">
      <LeftSideCanvas title={t('title')} subtitle={t('subtitle')} text={t('text')} />

      <Paper
        className="h-full w-full sm:h-auto md:flex md:h-full py-32 px-16 sm:p-48 md:p-40 md:px-96 sm:rounded-2xl md:rounded-none sm:shadow md:shadow-none rtl:border-r-1 ltr:border-l-1"
        sx={{ background: (theme) => theme.palette.background?.default }}
      >
        <div className="w-full mx-auto sm:mx-0">
          <Typography className="text-4xl font-extrabold tracking-tight leading-tight">
            {t('sign_up')}
          </Typography>
          <div className="flex items-baseline mt-10 font-medium">
            <Typography>{t('have_account')}</Typography>
            <Link className="ml-4 text-secondary-main underline" to="/sign-in">
              {t('sign_in')}
            </Link>
          </div>

          <form
            name="signupForm"
            noValidate
            className="flex flex-col justify-center w-full mt-48"
            onSubmit={handleSubmit(onSubmit)}
          >
            <Controller
              name="name"
              control={control}
              render={({ field }) => (
                <StyledTextField
                  {...field}
                  className="mb-28"
                  label={t('name')}
                  autoFocus
                  type="text"
                  error={!!errors.name}
                  helperText={errors?.name?.message}
                  variant="outlined"
                  required
                  fullWidth
                />
              )}
            />

            <Controller
              name="email"
              control={control}
              render={({ field }) => (
                <StyledTextField
                  {...field}
                  className="mb-28"
                  label={t('email')}
                  type="email"
                  error={!!errors.email}
                  helperText={errors?.email?.message}
                  variant="outlined"
                  required
                  fullWidth
                />
              )}
            />

            <Controller
              name="password"
              control={control}
              render={({ field }) => (
                <StyledTextField
                  {...field}
                  className="mb-28"
                  label={t('password')}
                  type="password"
                  error={!!errors.password}
                  helperText={errors?.password?.message}
                  variant="outlined"
                  required
                  fullWidth
                />
              )}
            />

            <Controller
              name="passwordConfirm"
              control={control}
              render={({ field }) => (
                <StyledTextField
                  {...field}
                  className="mb-28"
                  label={t('password_confirm')}
                  type="password"
                  error={!!errors.passwordConfirm}
                  helperText={errors?.passwordConfirm?.message}
                  variant="outlined"
                  required
                  fullWidth
                />
              )}
            />

            <div className="flex flex-col items-center justify-center gap-10 w-full">
              <Button
                variant="contained"
                color="secondary"
                className="max-w-320 mt-32 text-base uppercase rounded-xl"
                aria-label={t('sign_up_btn')}
                disabled={_.isEmpty(dirtyFields) || !isValid}
                type="submit"
                size="large"
              >
                {t('sign_up_btn')}
              </Button>
              {errors.root?.message && (
                <p className="text-l text-error-main">{errors.root?.message}</p>
              )}
            </div>
          </form>
        </div>
      </Paper>
    </div>
  );
}

export default withTranslation('signUpPage')(SignUpPage);
