import { Field, Form, Formik } from 'formik';
import Segment from './segment';
import { requiredTermsAndConditions } from './forms/validations';
import Button from './buttons/button';
import Alert from './alert';
import { useFormErrorMessage } from '../../hooks/index/use-form-error-message';
import { useCreateIntroducerMutation } from '../../hooks/react-query/use-introducer';
import { CreateIntroducerDataType, IntroducerType } from '../../api/introducer';
import { Link } from 'react-router-dom';
import FormCheckbox from './forms/checkbox';
import TermsAndConditions from '../termsAndConditions/terms-and-conditions';
import FormInput from './forms/input';

type CreateIntroducerFormDataType = CreateIntroducerDataType & {
  termsAndConditions: boolean;
};
type CreateIntroducerFormPropsType = {
  onSubmit?: (data: IntroducerType) => void;
};

function CreateIntroducerForm({ onSubmit }: CreateIntroducerFormPropsType) {
  const { formErrorMessage, setFormError } = useFormErrorMessage();
  const { mutate: createIntroducer } = useCreateIntroducerMutation();

  async function submit({
    termsAndConditions,
    ...createIntroducerData
  }: CreateIntroducerFormDataType) {
    await createIntroducer(createIntroducerData, {
      onSuccess: onSubmit,
      onError: setFormError
    });
  }

  return (
    <Segment dataTestId='create-introducer-form' className='p-6'>
      <Formik initialValues={{ iban: '', termsAndConditions: false }} onSubmit={submit}>
        {({ dirty }: { dirty: boolean }) => (
          <>
            {dirty && formErrorMessage && (
              <Alert content={formErrorMessage} className='mt-3 mb-5' />
            )}

            <Form noValidate data-testid='login-form' className='grid grid-cols-1 gap-5 py-3'>
              <TermsAndConditions className='m-0 max-h-[60vh] overflow-y-scroll bg-slate-100' />
              <Field name='iban' component={FormInput} type='hidden' />
              <Field
                required
                name='termsAndConditions'
                label={
                  <>
                    <Link to='/terms-and-conditions' target='_blank' className='text-indigo-600'>
                      شرایط و قوانین{' '}
                    </Link>
                    <span>را مطالعه کرده‌ام و آن‌ها را می‌پذیرم.</span>
                  </>
                }
                component={FormCheckbox}
                validate={requiredTermsAndConditions}
              />
              <Button type='submit' color='green' content='تایید' />
            </Form>
          </>
        )}
      </Formik>
    </Segment>
  );
}

export default CreateIntroducerForm;
