'use client';
import { useState } from 'react';
import { useGraphQlUsersList } from '@/pages/users/queries';
import { UserDataTableUpdate } from '@/pages/users/update/table/data-table';
import { UserForm } from '@/pages/users/update/form';
import { useSearchParams, useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button';

const PageUpdateUser = () => {
    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
    if (!uuid) {
        return <>
            <div>UUID not found in search params</div>
            <Button onClick={() => router.push('/users')}>Back to Users</Button>
        </>
    }

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

    if (!initData) {
        return <>
            <div>Selected User is either deleted or not found</div>
            <Button onClick={() => router.push('/users')}>Back to Users</Button>
        </>
    }

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

export { PageUpdateUser };
