'use client';
import { useState } from 'react';
import { BuildAreasDataTableAdd } from './table/data-table';
import { useGraphQlBuildAreasList } from '@/pages/build-areas/queries';
import { BuildAreasForm } from './form';
import { Button } from '@/components/ui/button';
import { useSearchParams, useRouter } from 'next/navigation';

const PageAddBuildAreas = () => {
    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 } = useGraphQlBuildAreasList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, buildId: buildId } });
    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 (
        <>
            <BuildAreasDataTableAdd
                data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch} buildId={buildId}
            />
            <BuildAreasForm refetchTable={refetch} buildId={buildId} />
        </>
    )
}

export { PageAddBuildAreas };
