import { useRef } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

import { IconInfoCircle } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import { StateCard } from '@material-hu/components/composed-components/StateCard';
import TaskFocusHeader from '@material-hu/components/design-system/Header/TaskFocus';
import TableLoader from '@material-hu/components/design-system/Table/components/TableLoader';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { useGetArticlesSearch } from '../../hooks/useGetArticlesSearch';
import { useSidebarSearchQuery } from '../../hooks/useSidebarSearchQuery';

import { SearchItem } from './SearchItem';
import { SearchLoading } from './SearchLoading';

// TODO: Move this component to material-hu to be used to in backoffice
export const ArticleSearchResults = () => {
  const containerRef = useRef<HTMLDivElement>(null);
  const { t } = useLokaliseTranslation('general');
  const { debouncedSearch, isSearchPending } = useSidebarSearchQuery();
  const navigate = useNavigate();
  const { pathname } = useLocation();

  const {
    visibleArticles,
    totalCount,
    isFetchingNextPage,
    handleFetchNextPage,
    isFetching,
    isError,
    isSuccess,
  } = useGetArticlesSearch(debouncedSearch);

  const handleScrollToTop = () => {
    containerRef.current?.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const isSearchSettled = !isFetching && !isSearchPending;
  const hasArticles = visibleArticles.length > 0;

  const showSkeleton =
    !isSearchSettled && !hasArticles && (!isError || isSearchPending);
  const showError = isError && isSearchSettled;
  const showEmpty = isSuccess && isSearchSettled && !hasArticles;
  const showResults = isSuccess && hasArticles;
  const dimResults = showResults && !isSearchSettled && !isFetchingNextPage;

  return (
    <Stack
      ref={containerRef}
      sx={{ width: '100%', mx: 'auto', overflow: 'auto' }}
    >
      <TaskFocusHeader
        title={t('search_result')}
        onBack={() => navigate(pathname, { replace: true })}
      />
      <Stack
        id="articles-page"
        sx={{
          p: 2,
          maxWidth: 'lg',
          gap: 2,
          mx: 'auto',
          width: '100%',
        }}
      >
        {showSkeleton && <SearchLoading />}
        {showError && (
          <StateCard
            slotProps={{
              title: {
                title: t('error_search_title'),
                description: t('error_description'),
              },
            }}
          />
        )}
        {showEmpty && (
          <StateCard
            Icon={IconInfoCircle}
            slotProps={{
              title: {
                title: t('empty_search_title'),
                description: t('empty_search_description'),
              },
            }}
          />
        )}
        {showResults && (
          <>
            <Stack
              sx={{
                gap: 2,
                opacity: dimResults ? 0.5 : 1,
                transition: dimResults ? 'opacity 0.2s ease-in-out' : 'none',
              }}
            >
              {visibleArticles.map(article => (
                <SearchItem
                  key={article?.id}
                  article={article}
                />
              ))}
            </Stack>
            {isFetchingNextPage && <SearchLoading />}
            <TableLoader
              onScrollToTop={handleScrollToTop}
              loadedCount={visibleArticles.length}
              totalCount={totalCount}
              onLoadMore={handleFetchNextPage}
              slotProps={{ button: { loading: isFetchingNextPage } }}
            />
          </>
        )}
      </Stack>
    </Stack>
  );
};
