import React, { useState, useEffect, useContext, useRef, useCallback } from "react";
import { useHistory } from "react-router-dom";
import { toast } from "react-toastify";

import Button from "@material-ui/core/Button";
import Dialog from "@material-ui/core/Dialog";
import Select from "@material-ui/core/Select";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import LinearProgress from "@material-ui/core/LinearProgress";
import { makeStyles } from "@material-ui/core";

import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogTitle from "@material-ui/core/DialogTitle";

import { i18n } from "../../translate/i18n";
import ButtonWithSpinner from "../ButtonWithSpinner";
import { AuthContext } from "../../context/Auth/AuthContext";

import toastError from "../../errors/toastError";

import api from "../../services/api";

const useStyles = makeStyles((theme) => ({
  maxWidth: {
    width: "100%",
  },
  paper: {
    minWidth: "300px"
  },
  linearProgress: {
    marginTop: "5px"
  }
}));

const ContactCreateTicketModal = ({ modalOpen, onClose, contactId }) => {
  const { user } = useContext(AuthContext);
  let isMounted = useRef(true)

  const history = useHistory();
  const [queues, setQueues] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectedQueue, setSelectedQueue] = useState('');
  const [itemHover, setItemHover] = useState(-1)
  const classes = useStyles();

  useEffect(() => {
    const userQueues = user.queues.map(({ id, name, color }) => { return { id, name, color } })
    if (userQueues.length === 1) setSelectedQueue(userQueues[0].id)
    setQueues(userQueues)
  }, [user]);

  const handleClose = () => {
    onClose();
  };

  const handleSaveTicket = useCallback(async (contactId, userId, queueId) => {
    if (!contactId || !userId) {
      console.log("Missing contactId or userId")
      return
    };
    if (!queueId) {
      toast.warning("Nenhuma Fila Selecionada")
      return
    }
    if (isMounted.current) setLoading(true);
 

    const delayDebounceFn = setTimeout(() => {
      const ticketCreate = async () => {
        try {
          const { data: ticket } = await api.post("/tickets", {
            contactId: contactId,
            userId: userId,
            queueId: queueId,
            status: "open",
          });
          history.push(`/tickets/${ticket.id}`);
        } catch (err) {
          toastError(err);
        }
        if (isMounted.current) setLoading(false);

      };
      ticketCreate();
    }, 300);
    return () => clearTimeout(delayDebounceFn);

  }, [history])

  useEffect(() => {
    if (modalOpen && queues.length <= 1) {
      handleSaveTicket(contactId, user.id, selectedQueue)
    }
    return () => {
      isMounted.current = false;
    };
  }, [modalOpen, contactId, user.id, selectedQueue, handleSaveTicket, queues.length]);

  if (modalOpen && queues.length <= 1) {
    return <LinearProgress />
  }

  return (
    <Dialog open={modalOpen} onClose={handleClose} maxWidth="xs" scroll="paper" classes={{ paper: classes.paper }}>
      <DialogTitle id="form-dialog-title">
        {i18n.t("newTicketModal.title")}
      </DialogTitle>
      <DialogContent dividers>
        <FormControl variant="outlined" className={classes.maxWidth}>
          <InputLabel>{i18n.t("Selecionar Fila")}</InputLabel>
          <Select
            value={selectedQueue}
            onChange={(e) => setSelectedQueue(e.target.value)}
            label={i18n.t("Filas")}
          >
            <MenuItem value={''}>&nbsp;</MenuItem>
            {queues.map(({ id, color, name }) => (
              <MenuItem
                key={id}
                value={id}
                onMouseEnter={() => setItemHover(id)}
                onMouseLeave={() => setItemHover(-1)}
                style={{
                  background: id !== itemHover ? "white" : color,
                }}
              >{name[0].toUpperCase() + name.slice(1).toLowerCase()}</MenuItem>
            ))}
          </Select>
        </FormControl>
      </DialogContent>
      <DialogActions>
        <Button
          onClick={handleClose}
          color="secondary"
          disabled={loading}
          variant="outlined"
        >
          {i18n.t("newTicketModal.buttons.cancel")}
        </Button>
        <ButtonWithSpinner
          onClick={() => handleSaveTicket(contactId, user.id, selectedQueue)}
          variant="contained"
          color="primary"
          loading={loading}
        >
          {i18n.t("newTicketModal.buttons.ok")}
        </ButtonWithSpinner>
      </DialogActions>
    </Dialog>
  );
};

export default ContactCreateTicketModal;