'use client';
import { TagSelect, VirtualGrid } from '@/components';
import { useInfiniteQuery } from '@tanstack/react-query';
import { useMemo } from 'react';

const request = async (params: any) => {
  const pageSize = 20;
  await new Promise((resolve) => setTimeout(resolve, 2000));
  return {
    rows: new Array(pageSize).fill(0).map((_, i) => ({
      id: `item_${params.index + i}`,
      name: `一个提示词${params.index + i}`,
    })),
    nextPage: params.index + pageSize,
    hasMore: params.index + pageSize < 80,
  };
};

export default function Novel() {
  const { data, fetchNextPage, hasNextPage, isLoading, isFetchingNextPage } =
    useInfiniteQuery<{ rows: any[]; nextPage: number; hasMore: boolean }>({
      initialPageParam: 1,
      queryKey: ['novels'],
      getNextPageParam: (lastPage) =>
        lastPage.hasMore ? lastPage.nextPage : undefined,
      queryFn: ({ pageParam }) => request({ index: pageParam }),
    });

  const options = [
    {
      label: 'tag1',
      value: 'tag1',
    },
    {
      label: 'tag2',
      value: 'tag2',
    },
    {
      label: 'tag3',
      value: 'tag3',
    },
  ];

  const dataSource = useMemo(() => {
    return data?.pages?.flatMap((page) => page.rows) || [];
  }, [data]);

  return (
    <div className="h-full">
      <VirtualGrid
        padding={{ left: 50, right: 50 }}
        dataSource={dataSource}
        isFirstLoading={isLoading}
        isLoadingMore={isFetchingNextPage}
        noMoreData={!hasNextPage}
        noMoreDataRender={null}
        loadMore={() => {
          fetchNextPage();
        }}
        header={
          <TagSelect
            options={options}
            mode="multiple"
            render={(item) => `# ${item.label}`}
            className="mx-12.5 my-7.5"
          />
        }
        className="h-full"
        rowHeight={300}
        keySetter={(item) => item.id}
        columnCalc={(width) => Math.floor(width / 200)}
        itemRender={(item) => (
          <div className="relative h-full w-full rounded-md border border-gray-200 p-1">
            <span>{item.name}</span>
          </div>
        )}
      />
    </div>
  );
}
