import React from 'react';
import { Grid, TextField, Button } from '@material-ui/core';
import { Formik, Form, Field } from 'formik';
import { post } from '../../requests';
import { Event } from '../../types';

interface PropTypes {
  mutate: () => void;
}

interface Fields {
  name: string;
  schedule: string;
  attendanceId: string;
  conferenceId: string;
}

const EventForm: React.FC<PropTypes> = ({ mutate }) => {
  const handleSubmit = (fields: Fields, { resetForm }: any) => {
    const { name, schedule, attendanceId, conferenceId } = fields;

    if (schedule && conferenceId) {
      const event: Partial<Event> = {
        type: 'class',
        schedule,
        context: {
          name,
          attendanceId,
          conferenceId,
          participants: []
        }
      };

      return post('/events', event).then(() => {
        mutate();
        resetForm();
      });
    }
  }

  return (
    <Formik
      initialValues={{ name: '', schedule: '* * * * *', attendanceId: '', conferenceId: '' }}
      onSubmit={handleSubmit}
    >
      {({ values, errors, touched, isSubmitting }) => (
        <Form autoComplete="off">
          <Grid container spacing={2}>
            <Grid item sm={6} xs={12}>
              <Field
                name="name"
                label="Name"
                value={values.name}
                variant="outlined"
                fullWidth
                required
                as={TextField}
              />
            </Grid>
            <Grid item sm={6} xs={12}>
              <Field
                name="schedule"
                label="Schedule"
                value={values.schedule}
                variant="outlined"
                fullWidth
                required
                as={TextField}
              />
            </Grid>
            <Grid item sm={6} xs={12}>
              <Field
                name="conferenceId"
                label="Conference ID"
                value={values.conferenceId}
                variant="outlined"
                fullWidth
                required
                as={TextField}
              />
            </Grid>
            <Grid item sm={6} xs={12}>
              <Field
                name="attendanceId"
                label="Attendance ID"
                value={values.attendanceId}
                variant="outlined"
                fullWidth
                as={TextField}
              />
            </Grid>
            <Grid item sm={2} xs={12}>
              <Button
                type="submit"
                variant="contained"
                size="large"
                color="primary"
                fullWidth
              >
                Create event
              </Button>
            </Grid>
          </Grid>
        </Form>
      )}
    </Formik>
  );
};

export default EventForm;
