'use client';

import { useState } from 'react';
import { Plus, UploadCloud } from 'lucide-react';

import { PageHeader } from '@/components/page-header';
import { Button } from '@/components/ui/button';
import type { UploadListItem } from '@/types';

import { CreateUploadDialog } from './components/CreateUploadDialog';
import { useUploadListColumns } from './components/UploadListColumns';
import { UploadTable } from './components/UploadTable';
import { UploadVideoDialog } from './components/UploadVideoDialog';
import { useUploadFilters } from './hooks/useUploadFilters';
import { useUploadListEvents } from './hooks/useUploadListEvents';
import { useUploadsQuery } from './hooks/useUploadQueries';

export default function UploadPage() {
  const { skip, setSkip, limit, setLimit } = useUploadFilters();
  const uploadsQuery = useUploadsQuery({ skip, limit });
  useUploadListEvents();
  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const [videoUpload, setVideoUpload] = useState<UploadListItem | null>(null);

  const uploads = uploadsQuery.data?.items ?? [];
  const total = uploadsQuery.data?.total ?? 0;
  const isLoading = uploadsQuery.isLoading;

  const columns = useUploadListColumns(setVideoUpload);

  return (
    <>
      <main className="space-y-5">
        <PageHeader
          title="Uploads"
          description="Track uploaded road inspection videos, processing progress, and results."
          icon={UploadCloud}
          actions={
            <Button onClick={() => setIsCreateOpen(true)} size="sm">
              <Plus className="size-4" />
              Upload New
            </Button>
          }
        />

        <UploadTable
          columns={columns}
          uploads={uploads}
          isLoading={isLoading}
          skip={skip}
          limit={limit}
          total={total}
          onPageChange={setSkip}
          onLimitChange={setLimit}
        />
      </main>

      <CreateUploadDialog open={isCreateOpen} onOpenChange={setIsCreateOpen} />
      <UploadVideoDialog
        upload={videoUpload}
        open={Boolean(videoUpload)}
        onOpenChange={(open) => {
          if (!open) setVideoUpload(null);
        }}
      />
    </>
  );
}
