import { useEffect } from "react";
import { Box, Button, useTheme } from "@mui/material";
import SearchOutlinedIcon from '@mui/icons-material/SearchOutlined';
import HighlightOffOutlinedIcon from '@mui/icons-material/HighlightOffOutlined';
import { enqueueSnackbar } from 'notistack';
import { GetTicketsRequest, Ticket } from "@root/model/ticket";
import { setTickets, addOrUpdateTicket, useTicketStore } from "@root/stores/tickets";
import TicketItem from "./TicketItem";
import { getTickets, subscribeToAllTickets } from "@root/api/tickets";
import Chat from "./Chat";


export default function Support() {
    const theme = useTheme();
    const tickets = useTicketStore(state => state.tickets);

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

        getTickets({
            body: getTicketsBody,
            signal: controller.signal,
        }).then(result => {
            console.log("GetTicketsResponse", result);
            setTickets(result.data);
        }).catch(error => {
            console.log("Error fetching tickets", error);
            enqueueSnackbar(error.message);
        });

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

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

        const unsubscribe = subscribeToAllTickets({
            accessToken: token,
            onMessage(event) {
                console.log("SSE: ticket received:", event.data);
                try {
                    const newTicket = JSON.parse(event.data) as Ticket;
                    addOrUpdateTicket(newTicket);
                } catch (error) {
                    console.log("Error parsing ticket SSE", error);
                }
            },
            onError(event) {
                console.log("SSE Error:", event);
            }
        });

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

    return (
        <Box sx={{
            width: "100%",
            display: "flex",
            justifyContent: "space-between",
            height: "600px",
        }}>
            <Chat />
            <Box sx={{
                width: "max(40%, 460px)",
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
            }}>
                <Box sx={{
                    width: "100%",
                    border: "1px solid",
                    borderColor: theme.palette.grayDark.main,
                    borderRadius: "3px",
                    padding: "10px"
                }}>
                    <Button
                        variant="contained"
                        sx={{
                            backgroundColor: theme.palette.grayDark.main,
                            width: "100%",
                            height: "45px",
                            fontSize: "15px",
                            fontWeight: "normal",
                            textTransform: "capitalize",
                            "&:hover": {
                                backgroundColor: theme.palette.menu.main
                            }
                        }}>
                        Поиск
                        <SearchOutlinedIcon />
                    </Button>
                    <Button
                        variant="text"
                        sx={{
                            width: "100%",
                            height: "35px",
                            fontSize: "14px",
                            fontWeight: "normal",
                            color: theme.palette.secondary.main,
                            border: "1px solid",
                            borderColor: theme.palette.golden.main,
                            borderRadius: 0,
                            "&:hover": {
                                backgroundColor: theme.palette.menu.main
                            }
                        }}>
                        ЗАКРЫТЬ ТИКЕТ
                        <HighlightOffOutlinedIcon />
                    </Button>
                </Box>
                <Box sx={{
                    width: "100%",
                    border: "1px solid",
                    borderColor: theme.palette.grayDark.main,
                    borderRadius: "3px",
                    overflow: "auto",
                    overflowY: "auto",
                    padding: "10px"
                }}>
                    {tickets.map(ticket =>
                        <TicketItem ticket={ticket} key={ticket.id} />
                    )}
                </Box>
            </Box>
        </Box>
    );
}