import { Link } from 'react-router-dom';
import { Field, Form, Formik } from 'formik';
import Segment from '../shared/segment';
import {
  gender,
  password,
  required,
  requiredTermsAndConditions
} from '../shared/forms/validations';
import FormInput from '../shared/forms/input';
import FormSelect from '../shared/forms/select';
import Button from '../shared/buttons/button';
import Alert from '../shared/alert';
import ButtonGroup from '../shared/buttons/button-group';
import { useFormErrorMessage } from '../../hooks/index/use-form-error-message';
import { useRegisterMutation, UseRegisterMutationDataType } from '../../hooks/react-query/use-auth';
import FormCheckbox from '../shared/forms/checkbox';

type RegisterFormDataType = UseRegisterMutationDataType & {
  rePassword: string;
  termsAndConditions: boolean;
};
type RegisterFormPropsType = {
  mobile: string;
  authKey: string;
  reset: () => void;
};

function RegisterForm({ mobile, authKey, reset }: RegisterFormPropsType) {
  const { formErrorMessage, setFormError } = useFormErrorMessage();
  const { mutate: registerUser } = useRegisterMutation();

  function validate({ password, rePassword }: RegisterFormDataType) {
    const errors: { rePassword?: string } = {};
    if (password !== rePassword) errors.rePassword = 'رمزهای عبور غیر یکسان هستند.';
    return errors;
  }

  async function submit(data: RegisterFormDataType) {
    const { rePassword, termsAndConditions, ...registerData } = data;
    await registerUser(registerData, {
      onSuccess: reset,
      onError: setFormError
    });
  }

  return (
    <Segment dataTestId='register-form'>
      <p className='my-4 text-center font-normal'>
        <span>شماره تلفن همراه: </span>
        <span>{mobile}</span>
      </p>
      <hr className='my-4' />

      <Formik
        initialValues={{
          mobile,
          authKey,
          firstName: '',
          lastName: '',
          gender: '',
          password: '',
          rePassword: '',
          iban: '',
          termsAndConditions: false
        }}
        onSubmit={submit}
        validate={validate}
      >
        {({ dirty }: { dirty: boolean }) => (
          <>
            {dirty && formErrorMessage && (
              <Alert content={formErrorMessage} className='mt-3 mb-5' />
            )}

            <Form noValidate data-testid='login-form' className='grid grid-cols-1 gap-5 py-3'>
              <Field id='username' name='mobile' component={FormInput} type='hidden' />
              <Field name='authKey' component={FormInput} type='hidden' />

              <Field
                required
                name='firstName'
                label='نام'
                component={FormInput}
                validate={required}
              />
              <Field
                required
                name='lastName'
                label='نام خانوادگی'
                component={FormInput}
                validate={required}
              />
              <Field
                required
                name='gender'
                label='جنسیت'
                component={FormSelect}
                options={GENDER_OPTIONS}
                validate={gender}
              />
              <Field
                required
                name='password'
                label='رمز عبور'
                type='password'
                component={FormInput}
                validate={password}
              />
              <Field
                required
                name='rePassword'
                label='تائید رمز عبور'
                type='password'
                component={FormInput}
                validate={required}
                autoComplete='off'
              />
              <Field name='iban' component={FormInput} type='hidden' />
              <Field
                required
                name='termsAndConditions'
                label={
                  <>
                    <Link to='/terms-and-conditions' target='_blank' className='text-indigo-600'>
                      شرایط و قوانین{' '}
                    </Link>
                    <span>را مطالعه کرده‌ام و آن‌ها را می‌پذیرم.</span>
                  </>
                }
                component={FormCheckbox}
                validate={requiredTermsAndConditions}
              />
              <ButtonGroup float>
                <Button type='submit' color='green' content='تایید' />
                <Button type='submit' content='بازگشت' onClick={reset} />
              </ButtonGroup>
            </Form>
          </>
        )}
      </Formik>
    </Segment>
  );
}

const GENDER_OPTIONS = [
  { name: 'جنسیت', text: 'جنسیت', value: '' },
  { name: 'مرد', text: 'مرد', value: 'M' },
  { name: 'زن', text: 'زن', value: 'F' }
];

export default RegisterForm;
