import { type FC, useEffect } from 'react';
import { Helmet } from 'react-helmet-async';
import { useInfiniteQuery } from 'react-query';
import { useNavigate, useParams } from 'react-router';

import Container from '@material-hu/mui/Container';
import Stack from '@material-hu/mui/Stack';

import HuBreadcrumbs from '@material-hu/components/design-system/Breadcrumbs';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';

import { EVENTS_SOCKETS } from 'src/constants/sockets';
import { useSocket } from 'src/contexts/SocketContext';
import useDocument from 'src/hooks/queryHooks/document';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { DocumentList } from 'src/pages/dashboard/documents/components/folder';
import {
  documentsKeys,
  dropDocumentListData,
  pushDocumentListData,
  setDocumentListData,
  setFolderData,
} from 'src/pages/dashboard/documents/queries';
import { documentsRoutes } from 'src/pages/dashboard/documents/routes';
import { getDocumentList } from 'src/services/documents';
import { type Document, type Folder as FolderType } from 'src/types/documents';
import { getDocumentsList } from 'src/utils/documents';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

const LIMIT = 10;

export const Folder: FC = () => {
  const { t } = useLokaliseTranslation('documents');
  const HuGoThemeProvider = useHuGoTheme();
  const { folderId } = useParams();
  const socket = useSocket();

  const navigate = useNavigate();

  const { data: folderDetailData } = useDocument(folderId, !!folderId);

  const {
    data = { pages: [], pageParams: [] },
    isLoading,
    isSuccess,
    isFetchingNextPage,
    hasNextPage,
    fetchNextPage,
  } = useInfiniteQuery(
    documentsKeys.document.list(folderId),
    ({ pageParam = 1 }) => getDocumentList(pageParam, LIMIT, Number(folderId)),
    {
      getNextPageParam: (_, pages) => {
        const { page, totalPages } = pages[pages.length - 1]?.data || {};

        return page < totalPages ? pages.length + 1 : undefined;
      },
      enabled: !!folderId,
    },
  );

  useEffect(() => {
    const updateFolder = (folder: FolderType) => {
      setFolderData(folder.id, folder);
    };

    socket.listenEvent(EVENTS_SOCKETS.DOCUMENT_FOLDER_UPDATED, updateFolder);

    return () => {
      socket.closeEvent(EVENTS_SOCKETS.DOCUMENT_FOLDER_UPDATED, updateFolder);
    };
  }, [socket]);

  useEffect(() => {
    const deleteDocument = (deleteData: { id: number }) => {
      dropDocumentListData(deleteData.id, Number(folderId));
    };

    const updateDocument = (document: Document) => {
      setDocumentListData(document.id, document, Number(folderId));
    };

    const addDocument = () => {
      pushDocumentListData(Number(folderId));
    };

    socket.listenEvent(EVENTS_SOCKETS.DOCUMENT_UPDATED, updateDocument);

    socket.listenEvent(EVENTS_SOCKETS.DOCUMENT_DELETED, deleteDocument);

    socket.listenEvent(EVENTS_SOCKETS.DOCUMENT_CREATED, addDocument);

    return () => {
      socket.closeEvent(EVENTS_SOCKETS.DOCUMENT_UPDATED, updateDocument);

      socket.closeEvent(EVENTS_SOCKETS.DOCUMENT_DELETED, deleteDocument);

      socket.closeEvent(EVENTS_SOCKETS.DOCUMENT_CREATED, addDocument);
    };
  }, [socket]);

  const folder = folderDetailData?.data;
  const documentList = getDocumentsList(data);

  const breadcrumbs = [
    {
      title: t('DOCUMENTS'),
      onClick: () => navigate('/documents'),
    },
    {
      title: folder?.name ?? '',
      onClick: () => navigate(documentsRoutes.folders.detail(Number(folderId))),
    },
  ];

  return (
    <HuGoThemeProvider>
      <Helmet>
        <title>{formatTitle(folder?.name ?? '')}</title>
      </Helmet>
      <Stack
        sx={{
          backgroundColor: theme => theme.palette.new.background.layout.default,
          height: '100%',
          overflow: 'auto',
        }}
      >
        <Container maxWidth="lg">
          <Stack sx={{ mt: 2, py: 2 }}>
            <HuBreadcrumbs links={breadcrumbs} />
            {isLoading && (
              <HuCardContainer sx={{ width: '100%', mt: 2 }}>
                {Array.from({ length: 3 }, (_, index) => (
                  <HuListItem
                    key={index}
                    loading
                  />
                ))}
              </HuCardContainer>
            )}
            {!isLoading && (
              <DocumentList
                list={documentList}
                isLoading={isLoading}
                isSuccess={isSuccess}
                fetchNextPage={fetchNextPage}
                hasNextPage={hasNextPage}
                isFetchingNextPage={isFetchingNextPage}
              />
            )}
          </Stack>
        </Container>
      </Stack>
    </HuGoThemeProvider>
  );
};

export default Folder;
