import { useState, useEffect, useCallback } from 'react' import * as api from '@/services/api' import type { PlannedLeaveDay } from '@/types' interface UsePlannedDaysResult { data: PlannedLeaveDay[] | null isLoading: boolean error: string | null refresh: () => Promise add: (payload: api.CreatePlannedDayPayload) => Promise update: (id: string, payload: api.UpdatePlannedDayPayload) => Promise remove: (id: string) => Promise } export function usePlannedDays(childId?: string): UsePlannedDaysResult { const [data, setData] = useState(null) const [isLoading, setIsLoading] = useState(false) const [error, setError] = useState(null) const fetch = useCallback(async () => { if (!childId) { // The child this data belongs to is gone (e.g. a logout cleared the // selection) — clear rather than leave the previous account's // planned days rendered until a new childId arrives. setData(null) setError(null) return } setIsLoading(true) setError(null) try { const response = await api.getPlannedDays(childId) setData(response) } catch (err) { setError(err instanceof Error ? err.message : 'Failed to fetch planned days') setData(null) } finally { setIsLoading(false) } }, [childId]) const add = useCallback( async (payload: api.CreatePlannedDayPayload) => { const result = await api.createPlannedDay(payload) await fetch() return result }, [fetch], ) const update = useCallback( async (id: string, payload: api.UpdatePlannedDayPayload) => { const result = await api.updatePlannedDay(id, payload) await fetch() return result }, [fetch], ) const remove = useCallback( async (id: string) => { await api.deletePlannedDay(id) await fetch() }, [fetch], ) useEffect(() => { fetch() }, [fetch]) return { data, isLoading, error, refresh: fetch, add, update, remove } }