import { type FC, useEffect } from 'react';
import { useInfiniteQuery } from 'react-query';
import { useNavigate } from 'react-router-dom';

import { type SearchControllerProps } from '@material-hu/hooks/useHuPagination';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { logEvent } from 'src/config/logging';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { librariesKeys } from 'src/pages/dashboard/libraries/queries';
import { librariesRoutes } from 'src/pages/dashboard/libraries/routes';
import { getLibraries } from 'src/services/libraries';
import { EventName } from 'src/types/amplitude';
import { type Library } from 'src/types/libraries';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getActiveLibraries } from 'src/utils/libraries';

import InfiniteList from 'src/components/list/InfiniteList';

import { useLibrariesTitle } from '../hooks/useLibrariesTitle';

import NavLibraryItem from './NavLibraryItem';

export type LibrarySidebarProps = {
  Search: FC<SearchControllerProps>;
};

export const LibrarySidebar = ({ Search }: LibrarySidebarProps) => {
  const { t } = useLokaliseTranslation('libraries');
  const { librariesTitle } = useLibrariesTitle();
  const navigate = useNavigate();
  const HuGoThemeProvider = useHuGoTheme();

  useEffect(() => {
    const input = document.querySelector(
      '#library-search-input-container input',
    );

    const handleSearchFocus = () => {
      logEvent(EventName.WIDGET_LIBRARY_SEARCH);
    };

    input?.addEventListener('focus', handleSearchFocus);

    () => {
      input?.removeEventListener('focus', handleSearchFocus);
    };
  }, []);

  const {
    data: librariesData,
    isLoading: isLoadingLibraries,
    hasNextPage: librariesHasNextPage,
    fetchNextPage: fetchNextLibrariesPage,
    isFetchingNextPage: librariesFetchingNextPage,
  } = useInfiniteQuery(
    librariesKeys.list(),
    ({ pageParam = 1 }) => getLibraries({ page: pageParam, limit: 15 }),
    {
      getNextPageParam: (lastPage, pages) => {
        const { page, totalPages } = pages[pages.length - 1]?.data || {};

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

  const librariesPages = librariesData?.pages || [];
  const libraries = getActiveLibraries(
    librariesPages.flatMap(page => page.data.items),
  );
  const lastLibraryPageData = librariesPages[librariesPages.length - 1]?.data;

  const handleSelectLibrary = (library: Library) => () =>
    navigate(librariesRoutes.library(library.id));

  return (
    <Stack
      sx={{
        backgroundColor: 'background.paper',
        borderRight: 1,
        borderColor: 'divider',
        width: 280,
        minWidth: 280,
        overflow: 'hidden',
      }}
    >
      <HuGoThemeProvider>
        <Stack
          id="library-search-input-container"
          sx={{
            px: 1,
            pt: 1.5,
            pb: 1,
          }}
        >
          <Search
            inputProps={{
              variant: 'custom',
            }}
          />
        </Stack>
      </HuGoThemeProvider>
      <Stack
        sx={{
          my: 3,
          px: 2,
        }}
      >
        <Typography sx={{ color: '#000000de', fontWeight: 500 }}>
          {librariesTitle}
        </Typography>
      </Stack>
      <Stack
        sx={{
          height: 'calc(-72px + 100%)',
          overflowY: 'auto',
        }}
      >
        <InfiniteList
          isLoading={isLoadingLibraries}
          fetchNextPage={fetchNextLibrariesPage}
          isFetchingNextPage={librariesFetchingNextPage}
          totalPages={lastLibraryPageData?.totalPages}
          isSuccess={!!libraries.length}
          isEmpty={!libraries.length}
          noResultsLabel={t('library.empty')}
          hasNextPage={librariesHasNextPage}
          sx={{
            mt: 1,
            pb: 1,
            px: 2,
          }}
        >
          {libraries?.map(library => (
            <NavLibraryItem
              key={library.id}
              id={library.id}
              title={library.title}
              icon={library.icon}
              onClick={handleSelectLibrary(library)}
            />
          ))}
        </InfiniteList>
      </Stack>
    </Stack>
  );
};

export default LibrarySidebar;
