import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import {
  Card,
  CardHeader,
  CardContent,
  CardActions,
  Button
} from '@material-ui/core';
import {
  FiberManualRecord as RunningIcon,
  Close as FailedIcon,
  Done as CompleteIcon,
  Timer as NotStartedIcon
} from '@material-ui/icons';
import { Event } from '../../types';
import requests from '../../requests';
import { useAuth } from '../../hooks/useAuth';

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

const useStyles = makeStyles(theme => ({
  actions: {
    display: 'flex',
    justifyContent: 'space-between'
  },
  title: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'flex-start',
    '& svg': {
      marginLeft: theme.spacing(1)
    }
  },
  running: {
    color: theme.palette.warning.main
  },
  complete: {
    color: theme.palette.success.main
  },
}));


const EventCard: React.FC<PropTypes> = ({ event, mutate }) => {
  const classes = useStyles();
  const { user } = useAuth();
  const {
    name,
    schedule,
    status,
    nextRunAt,
    lastRunAt,
    context: {
      participants,
      conferenceId,
      attendanceId
    }
  } = event;

  const joined = participants.findIndex(x => x === user?.username) >= 0;

  const handleJoin = () => {
    if (user) {
      const { context } = event;
      context.participants.push(user.username);

      return requests
        .patch(`/events/${event._id}`, { context })
        .then(() => mutate());
    }
  };

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

  const title = (
    <div className={classes.title}>
      {name}
      {status === 'running' && <RunningIcon className={classes.running}/>}
      {status === 'complete' && <CompleteIcon className={classes.complete} />}
      {status === 'failed' && <FailedIcon color="error" />}
      {status === 'notStarted' && <NotStartedIcon color="disabled" />}
    </div>
  );

  return (
    <Card variant="outlined">
      <CardHeader title={title} subheader={schedule} />
      <CardContent>
        {nextRunAt && <div> Next run at: {new Date(nextRunAt).toLocaleTimeString()} </div>}
        {lastRunAt && <div> Last run at: {new Date(lastRunAt).toLocaleTimeString()} </div>}
        {conferenceId && <div> ConferenceID: {conferenceId} </div>}
        {attendanceId && <div> AttendanceID: {attendanceId} </div>}
        <div>
          Participants ({participants?.length || 0} / 3)
          <ul>
            {participants?.map(username => (
              <li> {username} {username === user?.username && <b>(you)</b>} </li>
            ))}
          </ul>
        </div>
      </CardContent>
      <CardActions className={classes.actions}>
        <Button
          onClick={handleRemove}
          color="primary"
          size="large"
        >
          Remove
        </Button>
        {!joined && (participants?.length || 0) < 3 && (
          <Button
            onClick={handleJoin}
            variant="contained"
            color="primary"
            size="large"
          >
            Join
          </Button>
        )}
        </CardActions>
    </Card>
  );
};

export default EventCard;
