import { createContext, useContext, useState } from 'react' import type { ReactNode } from 'react' import { useMutation, useQuery } from '@tanstack/react-query' import type { AbsenceDetails } from '@gruperly/shared' import { useToast } from '../../components/ui' import { ApiError, getAbsenceDetails, publicNotifyAbsence } from '../../lib/api' import { errorMessage } from '../../i18n' import { i18n } from '../../i18n/instance' type AbsenceNotifyContextValue = { token: string details: AbsenceDetails | undefined detailsPending: boolean detailsFailed: boolean isNotified: (session: { notified: boolean; sessionId: string }) => boolean isNotifying: (sessionId: string) => boolean notify: (sessionId: string) => void } const AbsenceNotifyContext = createContext(null) export function AbsenceNotifyProvider({ token, children }: { token: string; children: ReactNode }) { const toast = useToast() const [locallyNotified, setLocallyNotified] = useState([]) const detailsQuery = useQuery({ queryKey: ['absence-details', token], queryFn: () => getAbsenceDetails(token), enabled: Boolean(token), retry: 1, }) const notifyMutation = useMutation({ mutationFn: (sessionId: string) => publicNotifyAbsence({ token, classSessionId: sessionId }), onSuccess: (_data, sessionId) => { setLocallyNotified((prev) => [...prev, sessionId]) toast.success(i18n.t('public:absence.done'), i18n.t('public:absence.doneTitle')) }, onError: (error: unknown) => { if (error instanceof ApiError && error.problem?.status === 404) { toast.error(i18n.t('public:absence.invalidLink')) return } toast.error(errorMessage(error, i18n.t('public:absence.error'))) }, }) const value: AbsenceNotifyContextValue = { token, details: detailsQuery.data, detailsPending: detailsQuery.isPending, detailsFailed: detailsQuery.isError, isNotified: (session) => session.notified || locallyNotified.includes(session.sessionId), isNotifying: (sessionId) => notifyMutation.isPending && notifyMutation.variables === sessionId, notify: (sessionId) => notifyMutation.mutate(sessionId), } return {children} } export function useAbsenceNotify() { const context = useContext(AbsenceNotifyContext) if (!context) { throw new Error('useAbsenceNotify debe usarse dentro de ') } return context }