import { Link } from 'react-router-dom';
import { Field, Form, Formik } from 'formik';
import { toast } from 'react-hot-toast';
import Segment from '../../shared/segment';
import { requiredIban } from '../../shared/forms/validations';
import Button from '../../shared/buttons/button';
import Alert from '../../shared/alert';
import { useFormErrorMessage } from '../../../hooks/index/use-form-error-message';
import FormInput from '../../shared/forms/input';
import { useCreateSettleRequestMutation } from '../../../hooks/react-query/use-settle-request';
import { CreateSettleRequestDataType } from '../../../api/settle-request';

export type CreateSettleRequestFormPropsType = { initialIban?: string };

function CreateSettleRequestForm({ initialIban = '' }: CreateSettleRequestFormPropsType) {
  const { formErrorMessage, setFormError, resetFormErrorMessage } = useFormErrorMessage();
  const { mutate: createSettleRequest } = useCreateSettleRequestMutation();

  function onSuccess() {
    toast.success('درخواست تسویه شما با موفقیت ثبت شد.');
  }

  async function submit(data: CreateSettleRequestDataType) {
    resetFormErrorMessage();
    await createSettleRequest(data, {
      onSuccess,
      onError: setFormError
    });
  }

  return (
    <Segment dataTestId='create-settle-request-form' className='rounded-lg p-8'>
      <Formik initialValues={{ iban: initialIban }} onSubmit={submit}>
        {() => {
          return (
            <>
              {formErrorMessage && (
                <Alert className='mt-3 mb-5'>
                  <p>{formErrorMessage}</p>
                  <p className='mt-1 text-sm font-normal'>
                    <span>برای اطلاعات بیشتر به بخش </span>
                    <Link to='/terms-and-conditions' target='_blank' className='text-blue-600'>
                      شرایط و قوانین
                    </Link>
                    <span> مراجعه نمایید.</span>
                  </p>
                </Alert>
              )}

              <Form noValidate data-testid='login-form' className='grid grid-cols-1 gap-5 py-3'>
                <Field
                  required
                  name='iban'
                  label='شماره شبا'
                  prefix='IR-'
                  placeholder='123456789012345678901234'
                  component={FormInput}
                  type='tel'
                  maxLength={24}
                  validate={requiredIban}
                />
                <Button type='submit' color='green' content='درخواست تسویه حساب' />
              </Form>
            </>
          );
        }}
      </Formik>
    </Segment>
  );
}

export default CreateSettleRequestForm;
