import React, { useState, useContext, useMemo } from "react";
import { useHistory } from "react-router-dom";

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 { 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 api from "../../services/api";
import ButtonWithSpinner from "../ButtonWithSpinner";
import toastError from "../../errors/toastError";

import { WhatsAppsContext } from "../../context/WhatsApp/WhatsAppsContext";

const useStyles = makeStyles((theme) => ({
	maxWidth: {
		width: "100%",
	},
}));

// Receive array of queues arrays
// Return a new array with unique queues from all arrays has passed by the parameter
const queueArraysToOneArray = (array) => {
	if (!array) return []
	const map = {}
	const uniqueQueuesAvailable = []
	array.forEach((queues) => {
		queues.forEach(({ id, name, color }) => {
			if (!map[id]) {
				map[id] = true
				uniqueQueuesAvailable.push({ id, name, color })
			}
		})
	})
	return uniqueQueuesAvailable
}


const TransferTicketModal = ({ modalOpen, onClose, ticketid }) => {
	const history = useHistory();
	const { whatsApps } = useContext(WhatsAppsContext);
	const [loading, setLoading] = useState(false);
	const [selectedQueue, setSelectedQueue] = useState('');
	const classes = useStyles();
	const queues = useMemo(() => {
		if (!whatsApps) return [] 
		const whatsAppsQueues = whatsApps.map(({ queues }) => queues)
		//const whatsAppsQueues = whatsApps.filter(({ status }) => status === "CONNECTED" ).map(({ queues }) => queues)
		const uniqueQueuesAvailable = queueArraysToOneArray(whatsAppsQueues)
		return uniqueQueuesAvailable
	}, [whatsApps])
	const [itemHover, setItemHover] = useState(-1)

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

	const handleSaveTicket = async e => {
		e.preventDefault();
		if (!ticketid) return;
		if (!selectedQueue) return;
		setLoading(true);
		try {
			let data = {};

			if (selectedQueue && selectedQueue !== null) {
				data.queueId = selectedQueue
			}

			// test del PARA APARECER NA FILA DE OUTRO ATENDENTE E O MESMO CLICAR EM ACEITAR AO INVES DE ENVIAR PARA ATENDENDO
			data.status = 'pending'
			data.transfer = true 

			await api.put(`/tickets/${ticketid}`, data);

			setLoading(false);
			history.push(`/tickets`);
		} catch (err) {
			setLoading(false);
			toastError(err);
		}
	};

	return (
		<Dialog open={modalOpen} onClose={handleClose} maxWidth="lg" scroll="paper">
			<form onSubmit={handleSaveTicket}>
				<DialogTitle id="form-dialog-title">
					{i18n.t("transferTicketModal.title")}
				</DialogTitle>
				<DialogContent dividers>
					<FormControl variant="outlined" className={classes.maxWidth}>
						<InputLabel>{i18n.t("transferTicketModal.fieldQueueLabel")}</InputLabel>
						<Select
							value={selectedQueue}
							onChange={(e) => setSelectedQueue(e.target.value)}
							label={i18n.t("transferTicketModal.fieldQueuePlaceholder")}
							required
						>
							<MenuItem style={{ background: "white", }} value={''}>&nbsp;</MenuItem>
							{queues.map((queue) => (
								<MenuItem
									key={queue.id}
									value={queue.id}
									onMouseEnter={() => setItemHover(queue.id)}
									onMouseLeave={() => setItemHover(-1)}
									style={{
										background: queue.id !== itemHover ? "white" : queue.color,
									}}
								>{queue.name}
								</MenuItem>
							))}
						</Select>
					</FormControl>
				</DialogContent>
				<DialogActions>
					<Button
						onClick={handleClose}
						color="secondary"
						disabled={loading}
						variant="outlined"
					>
						{i18n.t("transferTicketModal.buttons.cancel")}
					</Button>
					<ButtonWithSpinner
						variant="contained"
						type="submit"
						color="primary"
						loading={loading}
					>
						{i18n.t("transferTicketModal.buttons.ok")}
					</ButtonWithSpinner>
				</DialogActions>
			</form>
		</Dialog >
	);
};

export default TransferTicketModal;