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/auth';

function LoginForm() {
  const {mutate} = useLoginMutation();

  return (
    <Segment>
      <Formik
        initialValues={{mobile: '', password: ''}}
        onSubmit={submit.bind(null, mutate)}
      >
        {({errors, dirty}) => (
          <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}
              />
              <Field
                required
                name='password'
                label='رمز عبور'
                type='password'
                component={FormInput}
                validate={required}
              />
              <ButtonGroup float>
                <Button type='submit' color='green' content='ورود'/>
              </ButtonGroup>
            </Form>
          </Fragment>
        )}
      </Formik>
    </Segment>
  );
}

async function submit(loginUser, data, {setErrors}) {
  try {
    await loginUser(data);
  } catch (error) {
    const errorMessage = error.message || 'شماره تلفن یا رمز عبور نادرست است.';
    setErrors({_error: errorMessage});
  }
}

export default LoginForm;
