'use client';
import { useState } from 'react';
import { BuildSitesForm } from '@/pages/build-sites/add/form';
import { BuildSitesDataTableAdd } from './table/data-table';
import { useGraphQlBuildSitesList } from '@/pages/build-sites/queries';
import { useSearchParams, useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';

const PageAddBuildSites = () => {
    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 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 };
    const { data, isLoading, error, refetch } = useGraphQlBuildSitesList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, buildID: buildId } });

    return (
        <>
            <BuildSitesDataTableAdd
                data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
            />
            <BuildSitesForm refetchTable={refetch} />
        </>
    )
}

export { PageAddBuildSites };
