import React, { useState } from 'react';
import { TicketType } from 'common/types';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import { useStyles } from './ticket-list-styles';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import Button from '@material-ui/core/Button';
import ClearIcon from '@material-ui/icons/Clear';
import { customFetch } from 'utils/fetch';

interface TicketTypeListProps {
  ticketTypes: TicketType[];
}

export const TicketTypeList: React.FC<TicketTypeListProps> = ({
  ticketTypes,
}) => {
  const [openDialog, setOpenDialog] = useState(false);
  const [item, setItem] = useState<TicketType>();
  const classes = useStyles();

  function handleClose(e: any) {
    setOpenDialog(false);
  }

  async function handleSubmitDialog(id: string) {
    await customFetch(`tickets/type/${id}`, {}, 'DELETE');
    setOpenDialog(false);
  }

  return (
    <>
      <List className={classes.list}>
        {ticketTypes.map(item => (
          <ListItem button className={classes.listItem}>
            <ListItemText>{item.label}</ListItemText>
            <ListItemIcon>
              <ClearIcon
                onClick={e => {
                  setItem(item);
                  setOpenDialog(true);
                }}
              />
            </ListItemIcon>
          </ListItem>
        ))}
      </List>
      {item && (
        <Dialog open={openDialog}>
          <DialogTitle classes={{ root: classes.dialogTitle }}>
            Skutečne si přejete zmazat tento typ lístku?
          </DialogTitle>
          <DialogContent dividers>
            <DialogContentText>{item.label}</DialogContentText>
          </DialogContent>
          <DialogActions>
            <Button onClick={handleClose} color="primary">
              Zrušit
            </Button>
            <Button
              onClick={e => handleSubmitDialog(item.id)}
              color="primary"
              autoFocus
              variant="contained"
            >
              Potvrdit
            </Button>
          </DialogActions>
        </Dialog>
      )}
    </>
  );
};
