import { Fragment } from 'react';
import { Field, Form, Formik } 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';

function MobileForm(props) {
  return (
    <Segment>
      <Formik initialValues={{ mobile: '' }} onSubmit={submit.bind(null, props)}>
        {({ errors, dirty, isSubmitting }) => (
          <Fragment>
            {dirty && errors._error && <Alert content={errors._error} className='mt-3 mb-5' />}
            <Form className='grid grid-cols-1 gap-5 p-3'>
              <Field
                required
                name='mobile'
                label='شماره تلفن همراه'
                type='tel'
                placeholder='09121234567'
                component={FormInput}
                validate={mobile}
              />
              <Button
                type='submit'
                color='green'
                content='تایید'
                disabled={!dirty || isSubmitting}
              />
            </Form>
          </Fragment>
        )}
      </Formik>
    </Segment>
  );
}

async function submit(props, { mobile }, { setErrors }) {
  try {
    await props.onSubmit(mobile);
  } catch (error) {
    setErrors({ _error: error.data.detail || error.data });
  }
}

export default MobileForm;
