import { Field, Form, Formik, FormikHelpers } from 'formik';
import Button from '../../shared/buttons/button';
import FormInput from '../../shared/forms/input';
import { smsKey } from '../../shared/forms/validations';
import { useCheckSmsKeyMutation } from '../../../hooks/react-query/use-temp-user';
import { CheckSmsKeyRequestDataType, CheckSmsKeyRequestReturnType } from '../../../api/temp-user';
import { useFormErrorMessage } from '../../../hooks/index/use-form-error-message';
import Alert from '../../shared/alert';
import { APIErrorType } from '../../../api';

export type SmsKeyFormPropsType = {
  mobile: string;
  onSubmit: (data: CheckSmsKeyRequestReturnType) => void;
  onError: (error: APIErrorType) => void;
};

function SmsKeyForm({ mobile, onSubmit, onError }: SmsKeyFormPropsType) {
  const { formErrorMessage, setFormErrorMessage } = useFormErrorMessage();
  const { mutate: checkSmsKeyRequest } = useCheckSmsKeyMutation();

  async function submit(
    values: CheckSmsKeyRequestDataType,
    { setErrors }: FormikHelpers<CheckSmsKeyRequestDataType>
  ) {
    await checkSmsKeyRequest(values, {
      onSuccess: onSubmit,
      onError: error => {
        if (error.status === 403) {
          onError(error);
        } else {
          setFormErrorMessage(error.data.smsKey);
          setErrors(error.data);
        }
      }
    });
  }

  return (
    <div data-testid='smskey-form'>
      <p className='my-4 text-center'>
        یک کد 6 رقمی برای شما ارسال شد، لطفا کد ارسال شده را وارد نمایید.
      </p>
      <Formik initialValues={{ mobile, smsKey: '' }} onSubmit={submit}>
        {({ dirty, isSubmitting }) => (
          <>
            {dirty && formErrorMessage && (
              <Alert content={formErrorMessage} className='mt-3 mb-5' />
            )}

            {/* form */}
            <Form noValidate>
              <Field id='username' name='mobile' component={FormInput} type='hidden' />
              <Field
                required
                name='smsKey'
                label='کد احراز هویت'
                placeholder='کد ارسال شده به شماره همراه'
                component={FormInput}
                type='tel'
                maxLength={6}
                validate={smsKey}
              />
              <Button
                color='green'
                type='submit'
                disabled={!dirty || isSubmitting}
                content='تایید'
                className='my-2 mr-auto'
              />
            </Form>
          </>
        )}
      </Formik>
    </div>
  );
}

export default SmsKeyForm;
