'use client';

import { useQuery } from '@tanstack/react-query';
import { observer } from 'mobx-react-lite';
import React from 'react';
import { useInView } from 'react-intersection-observer';

import { useStores } from '@/app/(root)/AppProviders';
import ResultFilters, {
  FilterConfig,
} from '@/components/filters/ResultFilters';
import { SongRowUIProps } from '@/components/song/SongRow';
import SongList from '@/components/song/Songlist';
import TitleText from '@/components/title/TitleText';
import { ContextType } from '@/logging/contextTypes';
import { Clip } from '@/state/clipStore';

const SimpleSongListPage = observer(
  ({
    loadContent,
    title,
    playlistId,
    contextId,
    contextType,
    songRowProps = {},
    isInfiniteScroll = true,
    filterConfig,
    filterValues,
  }: {
    loadContent: () => Promise<any>;
    title: string;
    playlistId: string;
    contextId: string;
    contextType: ContextType;
    songRowProps?: SongRowUIProps;
    isInfiniteScroll?: boolean;
    filterConfig?: FilterConfig;
    filterValues?: any[];
  }) => {
    const { clips: clipStore } = useStores();
    const { data, isLoading, refetch, isFetching } = useQuery({
      queryKey: [title, ...(filterValues?.filter((value) => !!value) || [])],
      queryFn: async () => {
        const data = await loadContent();
        clipStore.updateClips(data);
        return data;
      },
      refetchOnMount: true,
    });

    const { ref: spinnerRef } = useInView({
      threshold: 0,
      onChange: async (inView) => {
        if (inView && !isLoading && isInfiniteScroll) {
          refetch();
        }
      },
    });

    return (
      <div className='flex w-full flex-col overflow-y-auto pt-8'>
        <div className='ml-6 pb-2 font-bold'>
          <TitleText text={title} />
        </div>
        {filterConfig && (
          <ResultFilters filters={filterConfig} className='px-6 pb-4' />
        )}
        <SongList
          songs={data?.filter(
            (item: Clip) => !clipStore.notInterestedById[item.id]
          )}
          infiniteScrollLoadingRef={spinnerRef}
          isLoading={isLoading || isFetching}
          playlistId={playlistId}
          contextId={contextId}
          contextType={contextType}
          songRowProps={{
            showStats: true,
            showUser: true,
            trendingMode: true,
            showDislike: true,
            showModelTagOnly: true,
            ...songRowProps,
          }}
        />
      </div>
    );
  }
);

export default SimpleSongListPage;
