import { Typography, Box, useTheme, useMediaQuery, IconButton } from "@mui/material";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import { useParams } from "react-router-dom";
import SectionWrapper from "@components/SectionWrapper";
import ComplexNavText from "@components/ComplexNavText";
import SupportChat from "./SupportChat";
import CreateTicket from "./CreateTicket";
import TicketList from "./TicketList";
import { useEffect } from "react";
import { getTickets, subscribeToAllTickets } from "@root/api/tickets";
import { GetTicketsRequest, Ticket } from "@root/model/ticket";
import { updateTickets, setTicketCount, clearTickets, useTicketStore, setFetchState } from "@root/stores/tickets";
import { enqueueSnackbar } from "notistack";
import { authStore } from "@root/stores/makeRequest";


export default function Support() {
    const theme = useTheme();
    const upMd = useMediaQuery(theme.breakpoints.up("md"));
    const ticketId = useParams().ticketId;
    const currentPage = useTicketStore(state => state.currentPage);
    const ticketsPerPage = useTicketStore(state => state.ticketsPerPage);
    const token = authStore(state => state.token);

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

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

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

    useEffect(function subscribeToTickets() {
        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);
                    if ((newTicket as any).count) return; // Костыль пока бэк не починят
                    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();
            clearTickets();
        };
    }, [token]);

    return (
        <SectionWrapper
            maxWidth="lg"
            sx={{
                pt: upMd ? "25px" : "20px",
                pb: upMd ? "82px" : "43px",
                height: "100%",
            }}
        >
            {upMd && <ComplexNavText text1="Все тарифы — " text2="Запрос в службу техподдержки" />}
            <Box
                sx={{
                    mt: "20px",
                    mb: "40px",
                    display: "flex",
                    gap: "10px",
                }}
            >
                {!upMd && (
                    <IconButton sx={{ p: 0, height: "28px", width: "28px", color: "black" }}>
                        <ArrowBackIcon />
                    </IconButton>
                )}
                <Typography variant="h4">Запрос в службу техподдержки</Typography>
            </Box>
            {ticketId ? (
                <SupportChat />
            ) : (
                <Box
                    sx={{
                        display: "flex",
                        flexDirection: "column",
                        gap: upMd ? "40px" : "60px",
                    }}
                >
                    <CreateTicket />
                    <TicketList />
                </Box>
            )}
        </SectionWrapper>
    );
}
