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, updateTickets, useTicketStore } from "@root/stores/tickets";
import { enqueueSnackbar } from "notistack";
import { clearMessageState } from "@root/stores/messages";
import { getMessageFromFetchError, useSSESubscription, useTickets, useToken } from "@frontend/kitui";

export default function Support() {
    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();

    const ticketsFetchState = useTickets({
        url: "https://admin.pena.digital/heruvym/getTickets",
        ticketsPerPage,
        ticketApiPage,
        onNewTickets: result => {
            if (result.data) updateTickets(result.data);
        },
        onError: (error: Error) => {
            const message = getMessageFromFetchError(error);
            if (message) enqueueSnackbar(message);
        },
    });

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

    return (
        <Box
            sx={{
                display: "flex",
                width: "100%",
                flexDirection: upMd ? "row" : "column",
                gap: "12px",
            }}
        >
            {!upMd && (
                <Collapse headerText="Тикеты">
                    <TicketList ticketsFetchState={ticketsFetchState} />
                </Collapse>
            )}
            <Chat />
            {upMd && <TicketList ticketsFetchState={ticketsFetchState} />}
        </Box>
    );
}
