import { useFoodLogPhoto } from '@/see-log/hooks/useFoodLogPhoto'; import { useAlert } from '@/aesthetics/Alert'; import { usePreferences } from '@/profile/preferences'; import { useFoodLogs } from '@/see-log/home-page/useFoodLogs'; import { type FoodLogPred } from '@/types/foodlog'; import type { Strings } from '@/common/strings'; import { useLocalSearchParams, useRouter } from 'expo-router'; import { useEffect, useMemo, useState } from 'react'; export const useFoodLogDetail = (strings: Strings) => { const { id } = useLocalSearchParams<{ id: string }>(); const router = useRouter(); const { enabledCastleFeatures } = usePreferences(); const { getLogById, updateLog, deleteLog, getPredictions } = useFoodLogs(); const { showConfirm, showAlert } = useAlert(); const log = getLogById(id); const { uri: photoUri } = useFoodLogPhoto(log); const [editVisible, setEditVisible] = useState(false); const [editFoodName, setEditFoodName] = useState(log?.foodName ?? ''); const [predictions, setPredictions] = useState(null); const primaryPrediction = useMemo(() => predictions?.[0], [predictions]); useEffect(() => { if (!id) return; let cancelled = false; getPredictions(id) .then(data => !cancelled && setPredictions(data)) .catch(() => !cancelled && setPredictions([])); return () => { cancelled = true; }; }, [id, getPredictions]); const handleDelete = () => { if (!log) return; showConfirm(strings.common.delete, strings.seeLog.detail.deleteConfirmMessage, async () => { try { await deleteLog(log.id); router.back(); } catch { showAlert(strings.common.error, strings.seeLog.detail.deleteError); } }); }; const handleEdit = () => { if (!log) return; setEditFoodName(log.foodName); setEditVisible(true); }; const handleSaveEdit = async () => { if (!log) return; if (editFoodName.trim()) { try { await updateLog(log.id, { foodName: editFoodName.trim() }); setEditVisible(false); } catch { showAlert(strings.common.error, strings.seeLog.detail.updateError); } } }; return { log, photoUri, primaryPrediction, predictions, showAiComparison: enabledCastleFeatures.includes('compareAiModels'), editVisible, editFoodName, setEditVisible, setEditFoodName, handleDelete, handleEdit, handleSaveEdit, router, }; };