import { useEffect } from 'react';

import Box from '~/src/components/Box';
import Gradient from '~/src/components/Gradient';
import { InfiniteScroll } from '~/src/components/InfiniteScroll';
import Loading from '~/src/components/Loading';
import { PAGE_HEADER_HEIGHT } from '~/src/components/PageHeader';
import { useScroller } from '~/src/components/Scroller2';
import SearchTextInput from '~/src/components/SearchTextInput';
import Sticky from '~/src/components/Sticky';
import { useApiInfinite } from '~/src/hooks/useApi';
import useFetchSessionUser from '~/src/hooks/useFetchSessionUser';
import useTheme from '~/src/hooks/useTheme';
import { useI18n } from '~/src/lib/i18n';
import { getUserContentLinksApi } from '~/src/lib/songwhipApi/contentLinks/get';
import { ContentLinkItems, ContentLinksToolbar } from './components';
import { useContentLinksFilters } from './hooks';

export const ContentLinksTab = () => {
  const { t } = useI18n('catalog');

  const theme = useTheme();
  const scroller = useScroller();
  const { user, userAccountId } = useFetchSessionUser();
  const [filters, setFilters] = useContentLinksFilters();

  const { items, isLoading, isLoadingMore, hasError, hasMore, loadMore } =
    useApiInfinite(
      getUserContentLinksApi,
      (prev): Parameters<typeof getUserContentLinksApi> | null =>
        user?.id
          ? [
              user.id,
              {
                ...filters,
                accountId: userAccountId,
                cursor: prev?.cursor,
              },
            ]
          : null,
      {
        enabled: Boolean(user?.id),
        revalidateIfStale: false,
        keepPreviousData: true,
      }
    );

  // Reset scroll to top on filter change
  useEffect(() => {
    scroller?.setScrollTop(0);
  }, [filters.search, filters.sort, filters.artistId, scroller]);

  return (
    <Box>
      <Sticky zIndex={2} top={PAGE_HEADER_HEIGHT}>
        <Box flexColumn gap="2.4rem" style={{ background: theme.background }}>
          <SearchTextInput
            testId="catalogSearch"
            height="5rem"
            defaultValue={filters.search}
            placeholder={t('contentLinks.searchInputPlaceholder')}
            onInputEnd={({ value }) => {
              setFilters({ search: value || undefined });
            }}
            onClear={() => {
              setFilters({ search: undefined });
            }}
            withClearButton
            autoFocus
          />
          <ContentLinksToolbar />
        </Box>
        <Gradient to="transparent" from="#000" endAt="50%" height="2.4rem" />
      </Sticky>
      <Box zIndex={1}>
        {isLoading ? (
          <Loading margin="1.6rem 0" />
        ) : (
          <InfiniteScroll
            isLoading={isLoadingMore}
            hasError={hasError}
            hasMore={hasMore}
            onLoadMore={loadMore}
          >
            <ContentLinkItems items={items} />
          </InfiniteScroll>
        )}
      </Box>
    </Box>
  );
};
