import { Outlet } from "react-router-dom"
import Navbar from "./NavbarSite/Navbar"
import {
	Ticket,
	getMessageFromFetchError,
	useAllTariffsFetcher,
	usePrivilegeFetcher,
	useSSESubscription,
	useTicketsFetcher,
	useToken,
} from "@frontend/kitui"
import { updateTickets, setTicketCount, useTicketStore, setTicketsFetchState } from "@root/stores/tickets"
import { enqueueSnackbar } from "notistack"
import { updateTariffs } from "@root/stores/tariffs"
import { useCustomTariffs } from "@root/utils/hooks/useCustomTariffs"
import { setCustomTariffs } from "@root/stores/customTariffs"
import { useDiscounts } from "@root/utils/hooks/useDiscounts"
import { setDiscounts } from "@root/stores/discounts"
import { setPrivileges } from "@root/stores/privileges"

export default function ProtectedLayout() {
	const token = useToken()
	const ticketApiPage = useTicketStore((state) => state.apiPage)
	const ticketsPerPage = useTicketStore((state) => state.ticketsPerPage)

	useSSESubscription<Ticket>({
		url: `https://hub.pena.digital/heruvym/subscribe?Authorization=${token}`,
		onNewData: (data) => {
			updateTickets(data.filter((d) => Boolean(d.id)))
			setTicketCount(data.length)
		},
		marker: "ticket",
	})

	useTicketsFetcher({
		url: "https://hub.pena.digital/heruvym/getTickets",
		ticketsPerPage,
		ticketApiPage,
		onSuccess: (result) => {
			if (result.data) updateTickets(result.data)
			setTicketCount(result.count)
		},
		onError: (error: Error) => {
			const message = getMessageFromFetchError(error)
			if (message) enqueueSnackbar(message)
		},
		onFetchStateChange: setTicketsFetchState,
	})

	useAllTariffsFetcher({
		onSuccess: updateTariffs,
		onError: (error) => {
			const errorMessage = getMessageFromFetchError(error)
			if (errorMessage) enqueueSnackbar(errorMessage)
		},
	})

	useCustomTariffs({
		onNewUser: setCustomTariffs,
		onError: (error) => {
			if (error) enqueueSnackbar(error)
		},
	})

	useDiscounts({
		onNewDiscounts: setDiscounts,
		onError: (error) => {
			const message = getMessageFromFetchError(error)
			if (message) enqueueSnackbar(message)
		},
	})

	usePrivilegeFetcher({
		onSuccess: setPrivileges,
		onError: (error) => {
			console.log("usePrivilegeFetcher error :>> ", error)
		},
	})

	return (
		<Navbar>
			<Outlet />
		</Navbar>
	)
}
