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

const PageBuildAreas = () => {

    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 } = useGraphQlBuildAreasList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, buildId: buildId } });
    const handlePageChange = (newPage: number) => { setPage(newPage) };
    const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) };
    if (isLoading) { return <div className="flex items-center justify-center p-8">Loading...</div> }
    if (error) { return <div className="flex items-center justify-center p-8 text-red-500">Error loading build areas</div> }
    return <BuildAreasDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} buildId={buildId} />;

};

export { PageBuildAreas };
