import React from 'react';
import { Field, Form, Formik, ErrorMessage } from 'formik/dist/index';
import { TicketTypeTypes } from 'common/enums';
import { FormSelect } from 'components/form/form-select';
import { ticketTarrifs, ticketTypes, numberOfEntries } from './options';
import { customFetch } from 'utils/fetch';
import { CustomButton } from 'components/button/custom-button';
import * as Yup from 'yup';

const validationSchema = Yup.object().shape({
  type: Yup.string().required('Typ lístku je povinné pole'),
  tariff: Yup.string().required('Tarif je povinná položka'),
  number_of_entries: Yup.mixed().test('Počet vstupů', '', function(value) {
    const { createError, path } = this;

    const type = this.parent.type;

    if (type === 'MULTIPLE_ENTRY' && !value) {
      return createError({
        path,
        message: `Počet vstupů je povinná položka`,
      });
    } else return true;
  }),
});

export const TicketAdministrationForm = () => {
  return (
    <Formik
      initialValues={{
        type: undefined,
        tariff: undefined,
        number_of_entries: undefined,
      }}
      onSubmit={async (values, formikBag) => {
        await customFetch('tickets/type', values);
        formikBag.setSubmitting(false);
      }}
      validationSchema={validationSchema}
    >
      {({ values, errors, isSubmitting }) => (
        <Form style={{ display: 'flex', flexDirection: 'column' }}>
          <Field
            name="type"
            type="select"
            component={FormSelect}
            label="Typ lístku"
            options={ticketTypes}
          />
          <ErrorMessage
            name="type"
            render={msg => (
              <span style={{ color: '#F55044', marginBottom: 20 }}>{msg}</span>
            )}
          />

          <Field
            name="tariff"
            type="select"
            component={FormSelect}
            label="Tarif"
            options={ticketTarrifs}
          />
          <ErrorMessage
            name="tariff"
            render={msg => (
              <span style={{ color: '#F55044', marginBottom: 20 }}>{msg}</span>
            )}
          />

          {values.type === TicketTypeTypes.MULTIPLE_ENTRY && (
            <>
              <Field
                name="number_of_entries"
                label="Počet vstupů"
                type="select"
                component={FormSelect}
                options={numberOfEntries}
              />
              <ErrorMessage
                name="number_of_entries"
                render={msg => (
                  <span style={{ color: '#F55044', marginBottom: 20 }}>
                    {msg}
                  </span>
                )}
              />
            </>
          )}

          <CustomButton
            label="Vytvořit lístek"
            variant="outlined"
            size="medium"
            type="submit"
          />
        </Form>
      )}
    </Formik>
  );
};
