import { useEffect, useState } from 'react' import { classifyRecordError, fetchClientArchivePreview, setClientArchived, type ClientArchivePreview, type RecordFailureKind, } from '@faunosteo/supabase' import Button from '@/components/ui/Button' import Dialog from '@/components/ui/Dialog' import Notice from '@/components/ui/Notice' import { getSupabaseClient } from '@/lib/supabase' import { useT } from '@/i18n/useT' export interface ArchiveClientDialogProps { open: boolean clientId: string onClose: () => void /** Called once the server archived the client; the page then closes the dialog. */ onArchived: () => void } type Preview = | { status: 'loading' } | { status: 'ready'; preview: ClientArchivePreview } | { status: 'failed' } /** * Confirmation before archiving (contract ยง7.1): it lists the active animals * for which this client is the only current owner, then archives through * set_client_archived. Closing it is never a confirmation, and while the * request runs it refuses to close, so focus is restored once, after it. */ export default function ArchiveClientDialog({ open, clientId, onClose, onArchived, }: ArchiveClientDialogProps) { const t = useT() const [preview, setPreview] = useState({ status: 'loading' }) const [pending, setPending] = useState(false) const [failure, setFailure] = useState(null) useEffect(() => { if (!open) return let live = true setPreview({ status: 'loading' }) setFailure(null) const client = getSupabaseClient() if (!client) { setPreview({ status: 'failed' }) return } fetchClientArchivePreview(client, clientId) .then((result) => { if (live) setPreview({ status: 'ready', preview: result }) }) .catch(() => { if (live) setPreview({ status: 'failed' }) }) return () => { live = false } }, [open, clientId]) const close = () => { if (!pending) onClose() } async function confirm() { const client = getSupabaseClient() if (pending) return if (!client) return setFailure('unavailable') setPending(true) setFailure(null) try { await setClientArchived(client, clientId, true) onArchived() } catch (error) { setFailure(classifyRecordError(error)) } finally { setPending(false) } } const sole = preview.status === 'ready' ? preview.preview : null const others = sole ? sole.count - sole.animals.length : 0 return ( {t('clients.archive.body')}

} size="sm" >
{preview.status === 'loading' && (

{t('clients.archive.preview_loading')}

)} {preview.status === 'failed' && ( {t('clients.archive.preview_failed')} )} {sole && sole.count > 0 && (

{sole.count === 1 ? t('clients.archive.sole_owner_one') : t('clients.archive.sole_owner_other').replace( '{count}', String(sole.count), )}

    {sole.animals.map((animal) => (
  • {animal.name}
  • ))}
{others > 0 && (

{t('clients.archive.others').replace('{count}', String(others))}

)}
)} {failure && ( {t(`clients.failure.${failure}`)} )}
{/* Not disabled while pending: a button that turns disabled drops the focus out of the dialog. */}
) }