import { useCallback, useEffect, useRef, useState } from 'react' import { classifyRecordError, searchClients, type ClientListItem, type NameCursor, type RecordFailureKind, } from '@faunosteo/supabase' import { getSupabaseClient } from '@/lib/supabase' /** Time without typing before the term is sent: one search per pause, not per key. */ export const SEARCH_DELAY_MS = 300 export type ClientListState = | { status: 'loading' } | { status: 'ready' rows: ClientListItem[] next: NameCursor | null moreFailure: RecordFailureKind | null } | { status: 'error'; failure: RecordFailureKind } /** * The clients of the workspace for a term and the archived toggle: the * server searches (search_clients, POST), pages of 25 in name order, « Afficher * plus » appends the next page. An answer to an older term is dropped. */ export function useClientList(workspaceId: string) { const [query, setQuery] = useState('') const [term, setTerm] = useState('') const [archived, setArchived] = useState(false) const [state, setState] = useState({ status: 'loading' }) const [loadingMore, setLoadingMore] = useState(false) const [reload, setReload] = useState(0) const generation = useRef(0) useEffect(() => { const timer = setTimeout(() => setTerm(query.trim()), SEARCH_DELAY_MS) return () => clearTimeout(timer) }, [query]) useEffect(() => { const current = ++generation.current const client = getSupabaseClient() setState({ status: 'loading' }) if (!client) { setState({ status: 'error', failure: 'unavailable' }) return } searchClients(client, { workspaceId, query: term, archived }) .then((page) => { if (current === generation.current) setState({ status: 'ready', rows: page.rows, next: page.next, moreFailure: null, }) }) .catch((error: unknown) => { if (current === generation.current) setState({ status: 'error', failure: classifyRecordError(error) }) }) }, [workspaceId, term, archived, reload]) const loadMore = useCallback(async () => { const client = getSupabaseClient() if (state.status !== 'ready' || !state.next || !client || loadingMore) return const current = generation.current setLoadingMore(true) try { const page = await searchClients(client, { workspaceId, query: term, archived, after: state.next, }) if (current === generation.current) setState({ status: 'ready', rows: [...state.rows, ...page.rows], next: page.next, moreFailure: null, }) } catch (error) { if (current === generation.current) setState({ ...state, moreFailure: classifyRecordError(error) }) } finally { setLoadingMore(false) } }, [state, loadingMore, workspaceId, term, archived]) return { query, setQuery, /** The term the shown rows answer (the typed one after the pause). */ term, archived, setArchived, state, loadingMore, loadMore, retry: () => setReload((n) => n + 1), } }