import { Box, useMediaQuery, useTheme } from "@mui/material";
import { useEffect, useRef, useState } from "react";
import Chat from "./Chat/Chat";
import Collapse from "./Collapse";
import TicketList from "./TicketList/TicketList";
import { getTickets, subscribeToAllTickets } from "@root/api/tickets";
import { GetTicketsRequest, Ticket } from "@root/model/ticket";
import { clearTickets, updateTickets } from "@root/stores/tickets";
import { enqueueSnackbar } from "notistack";
import { clearMessages } from "@root/stores/messages";


const TICKETS_PER_PAGE = 20;

export default function Support() {
    const theme = useTheme();
    const upMd = useMediaQuery(theme.breakpoints.up("md"));
    const [currentPage, setCurrentPage] = useState<number>(0);
    const fetchingStateRef = useRef<"idle" | "fetching" | "all fetched">("idle");

    useEffect(function fetchTickets() {
        const getTicketsBody: GetTicketsRequest = {
            amt: TICKETS_PER_PAGE,
            page: currentPage,
            status: "open",
        };
        const controller = new AbortController();

        fetchingStateRef.current = "fetching";
        getTickets({
            body: getTicketsBody,
            signal: controller.signal,
        }).then(result => {
            console.log("GetTicketsResponse", result);
            if (result.data) {
                updateTickets(result.data);
                fetchingStateRef.current = "idle";
            } else fetchingStateRef.current = "all fetched";
        }).catch(error => {
            console.log("Error fetching tickets", error);
            enqueueSnackbar(error.message);
        });

        return () => controller.abort();
    }, [currentPage]);

    useEffect(function subscribeToTickets() {
        const token = localStorage.getItem("AT");
        if (!token) return;

        const unsubscribe = subscribeToAllTickets({
            accessToken: token,
            onMessage(event) {
                try {
                    const newTicket = JSON.parse(event.data) as Ticket;
                    console.log("SSE: parsed newTicket:", newTicket);
                    updateTickets([newTicket]);
                } catch (error) {
                    console.log("SSE: couldn't parse:", event.data);
                    console.log("Error parsing ticket SSE", error);
                }
            },
            onError(event) {
                console.log("SSE Error:", event);
            }
        });

        return () => {
            unsubscribe();
            clearMessages();
            clearTickets();
        };
    }, []);

    const incrementCurrentPage = () => setCurrentPage(prev => prev + 1);

    const ticketList = <TicketList fetchingStateRef={fetchingStateRef} incrementCurrentPage={incrementCurrentPage} />;

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