import { Box, useMediaQuery, useTheme } from "@mui/material";
import { useEffect } 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, setTicketsFetchState, updateTickets, useTicketStore } from "@root/stores/tickets";
import { enqueueSnackbar } from "notistack";
import { clearMessageState } from "@root/stores/messages";
import { authStore } from "@root/stores/auth";

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 = authStore((state) => state.token);

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

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

      return () => controller.abort();
    },
    [ticketApiPage, 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);
            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();
        clearMessageState();
        clearTickets();
      };
    },
    [token]
  );

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