'use client';
import { InfiniteScrollList } from '@/components/ui/infinite-scroll-list';
import AIStandardCard from '@/components/features/ai-standard-card';
import useSmartInfiniteQuery from '../../useSmartInfiniteQuery';
import { fetchCharacters } from '@/services/editor';
import { useHomeStore } from '../../store';
import { useEffect } from 'react';

const Character = () => {
  const selectedTags = useHomeStore((state) => state.selectedTags);

  const { dataSource, isFirstLoading, isLoadingMore, noMoreData, onLoadMore, onSearch } =
    useSmartInfiniteQuery<any, any>(fetchCharacters, {
      queryKey: 'characters',
      defaultQuery: { tagIds: selectedTags },
    });

  useEffect(() => {
    onSearch({ tagIds: selectedTags });
  }, [selectedTags]);

  return (
    <div className="mt-8">
      <InfiniteScrollList<any>
        items={dataSource}
        columns={(width) => {
          const cardWidth = width > 1200 ? 256 : width > 588 ? 200 : 170;
          return Math.floor(width / cardWidth);
        }}
        renderItem={(character) => <AIStandardCard character={character} />}
        getItemKey={(character) => character.id}
        hasNextPage={!noMoreData}
        isLoading={isFirstLoading || isLoadingMore}
        fetchNextPage={onLoadMore}
      />
    </div>
  );
};

export default Character;
