'use client';
import { TagSelect, VirtualGrid, Rate } from '@/components';
import React from 'react';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import { useInfiniteScroll } from '@/hooks/useInfiniteScroll';
import { fetchCharacters } from './service';
import { fetchTags } from '@/services/tag';
import { useQuery } from '@tanstack/react-query';
import Tags from '@/components/ui/Tags';

const RoleCard: React.FC<any> = React.memo(({ item }) => {
  const router = useRouter();
  return (
    <div
      onClick={() => router.push(`/character/${item.id}`)}
      className="cover-bg relative flex h-full w-full cursor-pointer flex-col justify-between overflow-hidden rounded-[20]"
      style={{
        backgroundImage: `url(${item.from || '/test.png'})`,
      }}
    >
      {/* from */}
      <Image src={item.from || '/test.png'} alt="from" width={55} height={78} />

      {/* info */}
      <div className="px-2.5 pb-3">
        <div title={item.name} className="truncate font-bold">
          {item.name}
        </div>
        <Tags
          className="mt-2.5"
          options={[
            { label: 'tag1', value: 'tag1' },
            { label: 'tag2', value: 'tag2' },
          ]}
        />
        <div className="text-text-color/60 mt-4 text-sm">
          {item.description}
        </div>
        <div className="flex justify-between">
          <Rate size="small" value={item.rate || 7} readonly />
          <div></div>
        </div>
      </div>
    </div>
  );
});

export default function Novel() {
  const {
    dataSource,
    isFirstLoading,
    isLoadingMore,
    noMoreData,
    onLoadMore,
    onSearch,
  } = useInfiniteScroll(fetchCharacters, {
    queryKey: 'characters',
  });

  // 使用useQuery查询tags
  const { data: tags } = useQuery({
    queryKey: ['tags'],
    queryFn: async () => {
      const res = await fetchTags();
      return res.rows?.map((tag: any) => ({
        label: tag.name,
        value: tag.id,
      }));
    },
  });

  return (
    <VirtualGrid
      padding={{ left: 50, right: 50 }}
      dataSource={dataSource}
      isFirstLoading={isFirstLoading}
      isLoadingMore={isLoadingMore}
      noMoreData={noMoreData}
      noMoreDataRender={null}
      loadMore={onLoadMore}
      header={
        <TagSelect
          options={tags}
          render={(item) => `# ${item.label}`}
          onChange={(v) => {
            onSearch({ tagId: v });
          }}
          className="mx-12.5 my-7.5 mb-7.5"
        />
      }
      gap={20}
      className="h-full"
      rowHeight={448}
      keySetter={(item) => item.id}
      columnCalc={(width) => Math.floor(width / 250)}
      itemRender={(item) => <RoleCard item={item} />}
    />
  );
}
