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

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

const EventForm: React.FC<PropTypes> = ({ mutate }) => {
  const [name, setName] = useState<string>('');
  const [date, setDate] = useState<string>((new Date()).toLocaleDateString());
  const [attendanceId, setAttendanceId] = useState<string>('');
  const [conferenceId, setConferenceId] = useState<string>('');

  const createHandler = (setter: any) => (event: React.ChangeEvent<HTMLInputElement>) => {
    setter(event.target.value);
  };

  const handleSubmit = () => {
    if (date && conferenceId) {
      const event: Event["data"] = {
        name,
        date,
        attendanceId,
        conferenceId,
        participants: []
      }

      setName('');
      setAttendanceId('');
      setConferenceId('');
      setDate('');

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

  return (
    <Grid container spacing={2}>
      <Grid item>
        <TextField
          value={name}
          onChange={createHandler(setName)}
          variant="outlined"
          label="Name"
        />
      </Grid>
      <Grid item>
        <TextField
          value={date}
          onChange={createHandler(setDate)}
          variant="outlined"
          label="Date"
          required
        />
      </Grid>
      <Grid item>
        <TextField
          value={conferenceId}
          onChange={createHandler(setConferenceId)}
          variant="outlined"
          label="Conference ID"
          required
        />
      </Grid>
      <Grid item>
        <TextField
          value={attendanceId}
          onChange={createHandler(setAttendanceId)}
          variant="outlined"
          label="Attendance ID"
        />
      </Grid>
      <Grid item xs={12}>
        <Button
          onClick={handleSubmit}
          variant="contained"
          size="large"
          color="primary"
        >
          CREATE JOB
        </Button>
      </Grid>
    </Grid>
  );
};

export default EventForm;
