import { Field, Form, Formik, FormikHelpers } from 'formik';
import Segment from '../shared/segment';
import Alert from '../shared/alert';
import FormInput from '../shared/forms/input';
import Button from '../shared/buttons/button';
import { mobile } from '../shared/forms/validations';
import { useCreateTempUserMutation } from '../../hooks/react-query/use-temp-user';
import { CreateTempUserDataType } from '../../api/temp-user';
import { useFormErrorMessage } from '../../hooks/index/use-form-error-message';

export type MobileFormData = CreateTempUserDataType;
export type MobileFormProps = { onSubmit: (data: MobileFormData) => void };

function MobileForm({ onSubmit }: MobileFormProps) {
  const { formErrorMessage, setFormError } = useFormErrorMessage();
  const { mutate: createTempUser } = useCreateTempUserMutation();

  async function submit(values: MobileFormData, { setErrors }: FormikHelpers<MobileFormData>) {
    createTempUser(values, {
      onSuccess: onSubmit,
      onError: error => {
        setFormError(error);
        setErrors({ mobile: error.data });
      }
    });
  }

  return (
    <Segment dataTestId='mobile-form'>
      <Formik initialValues={{ mobile: '' }} onSubmit={submit}>
        {({ dirty, isSubmitting }) => (
          <>
            {dirty && formErrorMessage && (
              <Alert content={formErrorMessage} className='mt-3 mb-5' />
            )}
            <Form noValidate className='grid grid-cols-1 gap-5 py-3'>
              <Field
                required
                name='mobile'
                label='شماره تلفن همراه'
                placeholder='09121234567'
                component={FormInput}
                type='tel'
                maxLength={11}
                validate={mobile}
              />
              <Button
                type='submit'
                color='green'
                content='تایید'
                disabled={!dirty || isSubmitting}
              />
            </Form>
          </>
        )}
      </Formik>
    </Segment>
  );
}

export default MobileForm;
