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

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

export { PageUpdateBuildParts };
