'use client';
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { useSearchParams, useRouter } from 'next/navigation'
import { UsersTypeDataTableUpdate } from './table/data-table';
import { useGraphQlUserTypesList } from '../queries';
import { UserTypesUpdateForm } from './form';

const PageUpdateUserTypes = () => {

    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 backToUserTypes = <><div>UUID not found in search params</div><Button onClick={() => router.push('/user-types')}>Back to Build</Button></>

    if (!uuid) { return backToUserTypes }
    const { data, isLoading, error, refetch } = useGraphQlUserTypesList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, uuid } });
    const initData = data?.data?.[0] || null;
    if (!initData) { return backToUserTypes }

    return (
        <>
            <UsersTypeDataTableUpdate
                data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
            />
            <UserTypesUpdateForm refetchTable={refetch} initData={initData} selectedUuid={uuid} />
        </>
    )
}

export { PageUpdateUserTypes };
