import { useLiveInfiniteQuery } from '@tanstack/react-db';
import { InView } from 'react-intersection-observer';

import { Container } from '@colanode/ui/components/layouts/containers/container';
import { Separator } from '@colanode/ui/components/ui/separator';
import { WorkspaceDownloadFile } from '@colanode/ui/components/workspaces/downloads/workspace-download-file';
import { WorkspaceDownloadsBreadcrumb } from '@colanode/ui/components/workspaces/downloads/workspace-downloads-breadcrumb';
import { useWorkspace } from '@colanode/ui/contexts/workspace';

const DOWNLOADS_PER_PAGE = 100;

export const WorkspaceDownloadsContainer = () => {
  const workspace = useWorkspace();

  const downloadsQuery = useLiveInfiniteQuery(
    (q) =>
      q
        .from({ downloads: workspace.collections.downloads })
        .orderBy(({ downloads }) => downloads.id, 'desc'),
    {
      pageSize: DOWNLOADS_PER_PAGE,
      getNextPageParam: (lastPage, allPages) =>
        lastPage.length === DOWNLOADS_PER_PAGE ? allPages.length : undefined,
    },
    [workspace.userId]
  );

  const downloads = downloadsQuery.data;

  return (
    <Container type="full" breadcrumb={<WorkspaceDownloadsBreadcrumb />}>
      <div className="overflow-y-auto">
        <div className="max-w-4xl space-y-10">
          <div>
            <h2 className="text-2xl font-semibold tracking-tight">Downloads</h2>
            <Separator className="mt-3" />
          </div>
          <div className="space-y-4 w-full">
            {downloads.map((download) => (
              <WorkspaceDownloadFile key={download.id} download={download} />
            ))}
          </div>
          <InView
            rootMargin="200px"
            onChange={(inView) => {
              if (inView && downloads.length === DOWNLOADS_PER_PAGE) {
                downloadsQuery.fetchNextPage();
              }
            }}
          />
        </div>
      </div>
    </Container>
  );
};
