'use client';
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { useSearchParams, useRouter } from "next/navigation";
import { useGraphQlBuildPartsList } from "./queries";
import { BuildPartsDataTable } from "./list/data-table";

const PageBuildPartsToBuild = () => {
    const [page, setPage] = useState(1);
    const [limit, setLimit] = useState(10);
    const [sort, setSort] = useState({ createdAt: 'desc' });
    const [filters, setFilters] = useState({});

    const searchParams = useSearchParams();
    const router = useRouter();
    const buildId = searchParams?.get('build');

    const { data, isLoading, error, refetch } = useGraphQlBuildPartsList({ limit: 10, skip: 0, sort: { createdAt: -1 }, filters: { ...filters, buildId } });

    const handlePageChange = (newPage: number) => { setPage(newPage) };
    const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) };

    const noUUIDFound = <>
        <div>Back To Builds. No uuid is found on headers</div>
        <Button onClick={() => router.push('/builds')}>Back to Builds</Button>
    </>

    if (!buildId) { return noUUIDFound }
    return <><BuildPartsDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} buildId={buildId} /></>
}

export default PageBuildPartsToBuild;
