import { Fragment } from 'react';
import { Field, Form, Formik } from 'formik';
import Segment from '../shared/segment';
import { mobile, required } from '../shared/forms/validations';
import FormInput from '../shared/forms/input';
import Button from '../shared/buttons/button';
import Alert from '../shared/alert';
import ButtonGroup from '../shared/buttons/button-group';
import { useLoginMutation } from '../../hooks/react-query/use-auth';
import { useFormErrorMessage } from '../../hooks/index/use-form-error-message';

type LoginData = { mobile: string; password: string };

function LoginForm() {
  const { formErrorMessage, setFormErrorMessage } = useFormErrorMessage();
  const { mutate: loginUser } = useLoginMutation();

  function setFormError() {
    setFormErrorMessage('شماره تلفن یا رمز عبور نادرست است.');
  }

  async function submit(data: LoginData) {
    await loginUser(data, { onError: setFormError });
  }

  return (
    <Segment dataTestId='login'>
      <Formik initialValues={{ mobile: '', password: '' }} onSubmit={submit}>
        {({ dirty }: { dirty: boolean }) => (
          <Fragment>
            {dirty && formErrorMessage && (
              <Alert content={formErrorMessage} className='mt-3 mb-5' />
            )}

            <Form data-testid='login-form' className='grid grid-cols-1 gap-5 py-3'>
              <Field
                required
                name='mobile'
                label='شماره تلفن همراه'
                placeholder='09121234567'
                component={FormInput}
                type='tel'
                maxLength={11}
                validate={mobile}
              />
              <Field
                required
                name='password'
                label='رمز عبور'
                type='password'
                component={FormInput}
                validate={required}
              />
              <ButtonGroup float>
                <Button type='submit' color='green' content='ورود' />
              </ButtonGroup>
            </Form>
          </Fragment>
        )}
      </Formik>
    </Segment>
  );
}

export default LoginForm;
