import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import {
  Card,
  CardHeader,
  CardContent,
  CardActions,
  Button
} from '@material-ui/core';
import { Event } from '../../types';
import requests from '../../requests';

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

const useStyles = makeStyles(theme => ({
  actions: {
    display: 'flex',
    justifyContent: 'space-between'
  }
}));

const EventCard: React.FC<PropTypes> = ({ event, mutate }) => {
  const classes = useStyles();
  const {
    data: {
      name,
      date,
      participants,
      conferenceId,
      attendanceId
    }
  } = event;

  const handleJoin = () => {
    // TODO: add your username to participants list
    const update = { data: { participants: [...participants, Math.random()] }}
    return requests
      .patch(`/events/${event._id}`, update)
      .then(() => mutate());
  };

  const handleRemove = () => {
    return requests
      .delete(`/events/${event._id}`)
      .then(() => mutate());
  };

  return (
    <Card variant="outlined">
      <CardHeader title={name || `Event #${event._id.slice(-4)}`} subheader={date}  />
      <CardContent>
        {conferenceId && <div> ConferenceID: {conferenceId} </div>}
        {attendanceId && <div> AttendanceID: {attendanceId} </div>}
        <div>
          Participants ({participants?.length || 0} / 3)
          <ul>
            {participants?.map(username => (
              <li> {username} </li>
            ))}
          </ul>
        </div>
      </CardContent>
      <CardActions className={classes.actions}>
        <Button
          onClick={handleRemove}
          color="primary"
          size="large"
        >
          Remove
        </Button>
        {(participants?.length || 0) < 3 && (
          <Button
            onClick={handleJoin}
            variant="contained"
            color="primary"
            size="large"
          >
            Join
          </Button>
        )}
        </CardActions>
    </Card>
  );
};

export default EventCard;
