'use client';
import { useState } from 'react';
import { BuildPartsDataTableAdd } from './table/data-table';
import { BuildPartsForm } from './form';
import { useGraphQlBuildPartsList } from '@/pages/build-parts/queries';
import { useRouter, useSearchParams } from 'next/navigation';
import { Button } from '@/components/ui/button';

const PageAddBuildParts = () => {
    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 (
        <>
            <BuildPartsDataTableAdd
                data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} buildId={buildId}
            />
            <BuildPartsForm refetchTable={refetch} selectedBuildId={buildId} />
        </>
    )
}

export { PageAddBuildParts };
