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

const PageBuildIbans = () => {

    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 } = useGraphQlBuildIbansList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, 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> }

    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 <BuildIbansDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} buildId={buildId} />;

};

export { PageBuildIbans };
