import { FC, useEffect } from 'react';
import { Helmet } from 'react-helmet-async';
import { useInfiniteQuery } from 'react-query';
import { useNavigate, matchPath, Outlet } from 'react-router-dom';

import 'src/pages/dashboard/tickets/i18n';

import Box from '@material-hu/mui/Box';
import { useTheme } from '@material-hu/mui/styles';
import useMediaQuery from '@material-hu/mui/useMediaQuery';

import { EVENTS_SOCKETS } from 'src/constants/sockets';
import { useAuth } from 'src/contexts/JWTContext';
import { useSocket } from 'src/contexts/SocketContext';
import useTicket from 'src/hooks/queryHooks/ticket';
import useGeneralError from 'src/hooks/useGeneralError';
import TicketList from 'src/pages/dashboard/tickets/components/TicketList';
import { useTranslation } from 'src/pages/dashboard/tickets/i18n';
import { ticketKeys } from 'src/pages/dashboard/tickets/queries';
import { ticketSkeletonRoutes } from 'src/pages/dashboard/tickets/routes';
import { updateTicketAssignment } from 'src/pages/dashboard/tickets/sockets';
import { getTicketList } from 'src/services/tickets';
import { TicketAgentStatus } from 'src/types/tickets';
import { formatTitle } from 'src/utils/helmetUtils';
import { getNextPage, getListItemsLength } from 'src/utils/pagination';

import Badge from 'src/components/Badge';
import ChatsSidebar from 'src/components/dashboard/chat/ChatsSidebar';
import { chatRoutes } from 'src/components/dashboard/chat/routes';
import Tabs from 'src/components/tabs';

const TICKET_PATH = ticketSkeletonRoutes.thread.detail();

const Tickets: FC = () => {
  const { user } = useAuth();
  const { t } = useTranslation();
  const showGeneralError = useGeneralError();
  const navigate = useNavigate();
  const socket = useSocket();
  const { ticketAgentStats } = useTicket();

  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

  const { data: agentStats } = ticketAgentStats(user.id);

  const dataTicketsUnassigned = useInfiniteQuery(
    ticketKeys.list.unassigned(),
    ({ pageParam = 1 }) =>
      getTicketList(user.id, pageParam, TicketAgentStatus.UNASSIGNED),
    {
      getNextPageParam: (lastPage, pages) =>
        getNextPage(getListItemsLength(pages), 20, pages),
      onError: err =>
        showGeneralError(err, t('ERROR_LOADING_TICKETS_UNASSIGNED')),
    },
  );

  const dataTicketsAssigned = useInfiniteQuery(
    ticketKeys.list.assigned(),
    ({ pageParam = 1 }) =>
      getTicketList(user.id, pageParam, TicketAgentStatus.PENDING),
    {
      getNextPageParam: (lastPage, pages) =>
        getNextPage(getListItemsLength(pages), 20, pages),
      onError: err =>
        showGeneralError(err, t('ERROR_LOADING_TICKETS_ASSIGNED')),
    },
  );

  const dataTicketsClosed = useInfiniteQuery(
    ticketKeys.list.closed(),
    ({ pageParam = 1 }) =>
      getTicketList(user.id, pageParam, TicketAgentStatus.CLOSED),
    {
      getNextPageParam: (lastPage, pages) =>
        getNextPage(getListItemsLength(pages), 20, pages),
      onError: err => showGeneralError(err, t('ERROR_LOADING_TICKETS_CLOSED')),
    },
  );

  const amountOfUnaasignedTickets =
    dataTicketsUnassigned?.data?.pages[0].data.count;
  const totalRedBubbleTickets =
    agentStats?.data?.amountOfTicketsWhichNeedAttention;

  useEffect(() => {
    socket.listenEvent(
      EVENTS_SOCKETS.UPDATE_TICKET_ASSIGNMENT,
      updateTicketAssignment,
    );

    return () => {
      socket.closeEvent(
        EVENTS_SOCKETS.UPDATE_TICKET_ASSIGNMENT,
        updateTicketAssignment,
      );
    };
  }, [socket]);

  const handleCancel = () => navigate(chatRoutes.chats());

  const tabs = [
    {
      id: t('UNASSIGNED_TAB'),
      title: (
        <>
          {t('UNASSIGNED_TAB')}
          <Badge count={amountOfUnaasignedTickets} />
        </>
      ),
      content: <TicketList {...dataTicketsUnassigned} />,
    },
    {
      id: t('ASSIGNED_TAB'),
      title: (
        <>
          {t('ASSIGNED_TAB')}
          <Badge count={totalRedBubbleTickets - amountOfUnaasignedTickets} />
        </>
      ),
      content: <TicketList {...dataTicketsAssigned} />,
    },
    {
      id: t('CLOSED_TAB'),
      title: t('CLOSED_TAB'),
      content: <TicketList {...dataTicketsClosed} />,
    },
  ];

  const isTicketThread = !!matchPath(
    {
      path: TICKET_PATH,
      end: false,
    },
    location.pathname,
  );

  const hideSidebar = isMobile && isTicketThread;

  const showChat = !isMobile || isTicketThread;

  return (
    <>
      <Helmet>
        <title>{formatTitle(t('TICKETS'))}</title>
      </Helmet>
      <Box
        sx={{
          backgroundColor: 'background.default',
          height: '100%',
          display: 'flex',
        }}
      >
        <>
          <Box
            sx={{
              display: 'flex',
              flex: 1,
              width: '100%',
            }}
          >
            <ChatsSidebar
              title={t('TICKETS')}
              hide={hideSidebar}
              onlyTitle
              onBackClick={handleCancel}
            >
              <Tabs
                id="tickets"
                tabs={tabs}
                tabsProps={{
                  variant: 'fullWidth',
                }}
                tabProps={{
                  wrapped: true,
                  sx: {
                    minWidth: '0px !important',
                  },
                }}
                tabPanelProps={{
                  withScrollbar: true,
                  options: { suppressScrollX: true },
                }}
              />
            </ChatsSidebar>
            {showChat && <Outlet />}
          </Box>
        </>
      </Box>
    </>
  );
};

export default Tickets;
