import { root } from '@repo/core' import { type ListTemplateGenerationsInput, type ListTemplateGenerationsResult, TemplateGenerationController, } from '@repo/sdk' import { useCallback, useRef, useState } from 'react' import { type ApiError } from '@/lib/types' import { handleError } from './use-error' export const useTemplateGenerations = () => { const [loading, setLoading] = useState(false) const [loadingMore, setLoadingMore] = useState(false) const [error, setError] = useState(null) const [data, setData] = useState() const currentPageRef = useRef(1) const hasMoreRef = useRef(true) const pageSize = 10 const load = useCallback(async (params?: ListTemplateGenerationsInput) => { setLoading(true) setError(null) currentPageRef.current = params?.page || 1 const templateGeneration = root.get(TemplateGenerationController) const { data, error } = await handleError( async () => await templateGeneration.list({ page: params?.page || 1, limit: params?.limit || pageSize, ...params, }), ) if (error) { setError(error) setLoading(false) return { data: undefined, error } } const items = data?.data || [] hasMoreRef.current = items.length >= (params?.limit || 20) setData(data) setLoading(false) return { data, error: null } }, []) const loadMore = useCallback( async (params?: Omit) => { if (loadingMore || loading || !hasMoreRef.current) return { data: undefined, error: null } setLoadingMore(true) const nextPage = currentPageRef.current + 1 const templateGeneration = root.get(TemplateGenerationController) const { data: newData, error } = await handleError( async () => await templateGeneration.list({ page: nextPage, limit: params?.limit || pageSize, ...params, }), ) if (error) { setLoadingMore(false) return { data: undefined, error } } const newItems = newData?.data || [] hasMoreRef.current = newItems.length >= (params?.limit || 20) currentPageRef.current = nextPage setData((prev) => ({ ...newData, data: [...(prev?.data || []), ...newItems], })) setLoadingMore(false) return { data: newData, error: null } }, [loading, loadingMore], ) const refetch = useCallback( (params?: ListTemplateGenerationsInput) => { hasMoreRef.current = true return load(params) }, [load], ) return { data, loading, loadingMore, error, load, refetch, loadMore, hasMore: hasMoreRef.current, } }