'use client';
import { useState } from 'react';
import { useGraphQlBuildTypesList } from '@/pages/build-types/queries';
import { BuildTypesDataTableUpdate } from '@/pages/build-types/update/table/data-table';
import { BuildTypesForm } from '@/pages/build-types/update/form';
import { useSearchParams, useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button';

const PageUpdateBuildTypes = () => {
    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 uuid = searchParams?.get('uuid') || null
    const backToBuildTypes = <>
        <div>UUID not found in search params</div>
        <Button onClick={() => router.push('/build-types')}>Back to Build Types</Button>
    </>
    if (!uuid) { return backToBuildTypes }
    const { data, isLoading, error, refetch } = useGraphQlBuildTypesList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, uuid } });
    const initData = data?.data?.[0] || null;
    if (!initData) { return backToBuildTypes }
    return (
        <>
            <BuildTypesDataTableUpdate
                data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit}
                onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
            />
            <BuildTypesForm refetchTable={refetch} initData={initData} selectedUuid={uuid} />
        </>
    )
}

export { PageUpdateBuildTypes };
