import { useActionQuery, useActionMutation, } from "@agent-native/core/client/hooks"; import { useT } from "@agent-native/core/client/i18n"; import type { Weight } from "@shared/types"; import { IconScale } from "@tabler/icons-react"; import { useState } from "react"; import { toast } from "sonner"; import { Skeleton } from "@/components/ui/skeleton"; import { isOptimisticLogRow, useOptimisticLogRows, } from "@/hooks/use-optimistic-log-rows"; import { formatLocalDate } from "@/lib/utils"; import { AddWeightDialog } from "./AddWeightDialog"; import { QueryErrorState } from "./QueryErrorState"; import { WeightCard } from "./WeightCard"; interface WeightTrackerProps { currentDate: Date; } export function WeightTracker({ currentDate }: WeightTrackerProps) { const t = useT(); const [editingWeight, setEditingWeight] = useState(null); const [editDialogOpen, setEditDialogOpen] = useState(false); const dateStr = formatLocalDate(currentDate); const deleteWeightMutation = useActionMutation("delete-weight", { onSuccess: () => { toast.success(t("weight.deleted")); }, onError: () => toast.error(t("weight.deleteFailed")), }); const weightsQuery = useActionQuery("list-weights", { date: dateStr, }); const { data: rawWeights, isLoading } = weightsQuery; const serverWeights = Array.isArray(rawWeights) ? rawWeights : []; const { rows: weights, hasOptimisticRows } = useOptimisticLogRows( "weight", serverWeights, dateStr, ); const todayWeight = weights[0]; return (

{t("weight.title")}

{!todayWeight && !isLoading && ( )} {editingWeight && ( { setEditDialogOpen(open); if (!open) setEditingWeight(null); }} currentDate={currentDate} /> )}
{isLoading && !hasOptimisticRows ? ( ) : weightsQuery.isError ? ( void weightsQuery.refetch()} /> ) : !todayWeight ? (

{t("weight.noneLogged")}

{t("weight.emptyDescription")}

) : ( { setEditingWeight(w); setEditDialogOpen(true); }} onDelete={(w) => { if (w.id) deleteWeightMutation.mutate({ id: String(w.id) }); }} isDeleting={deleteWeightMutation.isPending} isPending={isOptimisticLogRow(todayWeight)} /> )}
); }