import { useState, useEffect } from "react";
import { Box, useMediaQuery, useTheme } from "@mui/material";
import Chat from "./Chat/Chat";
import Collapse from "./Collapse";
import TicketList from "./TicketList/TicketList";
import { Ticket } from "@root/model/ticket";
import { clearTickets, setTicketsFetchState, updateTickets, useTicketStore } from "@root/stores/tickets";
import { enqueueSnackbar } from "notistack";
import { clearMessageState } from "@root/stores/messages";
import { getMessageFromFetchError, useSSESubscription, useTicketsFetcher, useToken } from "@frontend/kitui";
import ModalUser from "@root/pages/dashboard/ModalUser";

export default function Support() {
	const [openUserModal, setOpenUserModal] = useState<boolean>(false);
	const [activeUserId, setActiveUserId] = useState<string>("");
	const theme = useTheme();
	const upMd = useMediaQuery(theme.breakpoints.up("md"));
	const ticketsPerPage = useTicketStore((state) => state.ticketsPerPage);
	const ticketApiPage = useTicketStore((state) => state.apiPage);
	const token = useToken();

	useTicketsFetcher({
		url: process.env.REACT_APP_DOMAIN + "/heruvym/getTickets",
		ticketsPerPage,
		ticketApiPage,
		onSuccess: (result) => {
			if (result.data) updateTickets(result.data);
		},
		onError: (error: Error) => {
			const message = getMessageFromFetchError(error);
			if (message) enqueueSnackbar(message);
		},
		onFetchStateChange: setTicketsFetchState,
	});

	useSSESubscription<Ticket>({
		enabled: Boolean(token),
		url: process.env.REACT_APP_DOMAIN + `/heruvym/subscribe?Authorization=${token}`,
		onNewData: updateTickets,
		onDisconnect: () => {
			clearMessageState();
			clearTickets();
		},
		marker: "ticket",
	});

	useEffect(() => {
		if (!openUserModal) {
			setActiveUserId("");
		}
	}, [openUserModal]);

	useEffect(() => {
		if (activeUserId) {
			setOpenUserModal(true);

			return;
		}

		setOpenUserModal(false);
	}, [activeUserId]);

	return (
		<Box
			sx={{
				display: "flex",
				width: "100%",
				flexDirection: upMd ? "row" : "column",
				gap: "12px",
			}}
		>
			{!upMd && (
				<Collapse headerText="Тикеты">
					{(closeCollapse) => <TicketList closeCollapse={closeCollapse} setActiveUserId={setActiveUserId} />}
				</Collapse>
			)}
			<Chat />
			{upMd && <TicketList setActiveUserId={setActiveUserId} />}
			<ModalUser open={openUserModal} onClose={() => setOpenUserModal(false)} userId={activeUserId} />
		</Box>
	);
}
