// Database.js
'use client'

import { useEffect, useRef } from 'react';
import useSWRInfinite from 'swr/infinite';
import { debounce } from 'lodash-es';
import { useTranslation } from 'react-i18next';
import NewDatabaseCard from './NewDatabaseCard';
import DatasetCard from './DatabaseCard'; // 确保正确导入 DatasetCard 组件
import type { DataSetListResponse } from '@/models/datasets';
import { fetchDatasets } from '@/service/datasets';
import { useAppContext } from '@/context/app-context';
import { RiStackLine } from '@remixicon/react';
import { link } from 'fs';

const getKey = (
  pageIndex: number,
  previousPageData: DataSetListResponse,
  tags: string[],
  keyword: string,
) => {
  if (!pageIndex || previousPageData.has_more) {
    const params: any = {
      url: 'datasets',
      params: {
        page: pageIndex + 1,
        limit: 30,
      },
    };
    if (tags.length)
      params.params.tag_ids = tags;
    if (keyword)
      params.params.keyword = keyword;
    return params;
  }
  return null;
};

type Props = {
  containerRef: React.RefObject<HTMLDivElement>,
  tags: string[],
  keywords: string,
};

// 创建虚拟数据集
const mockDatasets = [
  {
    id: 'mock-1',
    name: '种植数据库',
    description: '',
    tags: [{ id: '1', name: '' }],
    provider: 'internal',
    embedding_available: true,
    document_count: 500,
    word_count: 100000,
    app_count: 3,
  },
  {
    id: 'mock-2',
    name: '病害数据库',
    description: '',
    tags: [{ id: '3', name: '' }],
    provider: 'internal',
    embedding_available: true,
    document_count: 300,
    word_count: 75000,
    app_count: 2,
  },
  {
    id: 'mock-3',
    name: '产量数据库',
    description: '',
    tags: [{ id: '5', name: '' }],
    provider: 'internal',
    embedding_available: true,
    document_count: 400,
    word_count: 90000,
    app_count: 4,
  },
];

const Database = ({
  containerRef,
  tags,
  keywords,
}: Props) => {
  const { isCurrentWorkspaceEditor } = useAppContext();
  const { data, isLoading, setSize, mutate } = useSWRInfinite(
    (pageIndex: number, previousPageData: DataSetListResponse) => getKey(pageIndex, previousPageData, tags, keywords),
    fetchDatasets,
    { revalidateFirstPage: false, revalidateAll: true },
  );
  const loadingStateRef = useRef(false);
  const anchorRef = useRef<HTMLAnchorElement>(null);

  const { t } = useTranslation();

  useEffect(() => {
    loadingStateRef.current = isLoading;
    document.title = `${t('dataset.knowledge')} - Dify`;
  }, [isLoading]);

  useEffect(() => {
    const onScroll = debounce(() => {
      if (!loadingStateRef.current) {
        const { scrollTop, clientHeight } = containerRef.current!;
        const anchorOffset = anchorRef.current!.offsetTop;
        if (anchorOffset - scrollTop - clientHeight < 100)
          setSize(size => size + 1);
      }
    }, 50);

    containerRef.current?.addEventListener('scroll', onScroll);
    return () => containerRef.current?.removeEventListener('scroll', onScroll);
  }, []);

  // Flatten the datasets array and concatenate with mock data if no real data is available yet.
  const allDatasets = data ? data.flatMap(({ data: datasets }) => datasets) : [];
  const displayedDatasets = mockDatasets.length > 0 ? mockDatasets : mockDatasets;

  return (
    <nav className='grid content-start grid-cols-1 gap-4 px-12 pt-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 grow shrink-0'>
      {isCurrentWorkspaceEditor && <NewDatabaseCard ref={anchorRef} />}
      {displayedDatasets.map(dataset => (
      
        <DatasetCard key={dataset.id} dataset={dataset} onSuccess={mutate} />
      
      ))}
    </nav>
  );
};

export default Database;