import { useCallback, useEffect, useMemo, useState } from 'react'; import { Alert, FlatList, Image, InteractionManager, KeyboardAvoidingView, Modal, Pressable, StyleSheet, TextInput, View, Platform, } from 'react-native'; import DateTimePicker from '@react-native-community/datetimepicker'; import * as ImagePicker from 'expo-image-picker'; import { ResizeMode, Video } from 'expo-av'; import { ThemedText } from '@/components/themed-text'; import { ThemedView } from '@/components/themed-view'; import { ThemedButton } from '@/components/themed-button'; import { IconButton } from '@/components/icon-button'; import { IconSymbol } from '@/components/ui/icon-symbol'; import { Colors, Fonts } from '@/constants/theme'; import { useTranslation } from '@/localization/i18n'; import { dbPromise, initCoreTables } from '@/services/db'; import { ZoomImageModal } from '@/components/zoom-image-modal'; import { useLocalSearchParams, useRouter } from 'expo-router'; import { useFocusEffect, useNavigation } from '@react-navigation/native'; import { useColorScheme } from '@/hooks/use-color-scheme'; type FieldRow = { id: number; name: string | null; }; type CropRow = { id: number; field_id: number | null; crop_name: string | null; }; type HarvestRow = { id: number; field_id: number | null; crop_id: number | null; harvested_at: string | null; quantity: number | null; unit: string | null; notes: string | null; photo_uri: string | null; field_name: string | null; crop_name: string | null; }; export default function HarvestsScreen() { const { t } = useTranslation(); const router = useRouter(); const navigation = useNavigation(); const params = useLocalSearchParams<{ from?: string | string[] }>(); const theme = useColorScheme() ?? 'light'; const palette = Colors[theme]; const fromParam = Array.isArray(params.from) ? params.from[0] : params.from; const unitPresets = [ { key: 'kg', value: 'kg' }, { key: 'g', value: 'g' }, { key: 'ton', value: 'ton' }, { key: 'pcs', value: 'pcs' }, ]; const [harvests, setHarvests] = useState([]); const [fields, setFields] = useState([]); const [crops, setCrops] = useState([]); const [status, setStatus] = useState(t('harvests.loading')); const [newModalOpen, setNewModalOpen] = useState(false); const [editModalOpen, setEditModalOpen] = useState(false); const [editingId, setEditingId] = useState(null); const [fieldModalOpen, setFieldModalOpen] = useState(false); const [cropModalOpen, setCropModalOpen] = useState(false); const [fieldModalTarget, setFieldModalTarget] = useState<'new' | 'edit'>('new'); const [cropModalTarget, setCropModalTarget] = useState<'new' | 'edit'>('new'); const [selectedFieldId, setSelectedFieldId] = useState(null); const [selectedCropId, setSelectedCropId] = useState(null); useEffect(() => { navigation.setOptions({ headerLeft: () => ( { if (fromParam === 'logbook') { router.replace('/logbook'); return; } if (fromParam === 'home') { router.replace('/'); return; } router.back(); }} hitSlop={10} style={{ paddingHorizontal: 8 }}> ), }); }, [fromParam, navigation, palette.text, router]); const [harvestDate, setHarvestDate] = useState(''); const [showHarvestPicker, setShowHarvestPicker] = useState(false); const [quantity, setQuantity] = useState(''); const [unit, setUnit] = useState('kg'); const [notes, setNotes] = useState(''); const [photoUri, setPhotoUri] = useState(null); const [errors, setErrors] = useState<{ field?: string; crop?: string; quantity?: string }>({}); const [editFieldId, setEditFieldId] = useState(null); const [editCropId, setEditCropId] = useState(null); const [editHarvestDate, setEditHarvestDate] = useState(''); const [showEditHarvestPicker, setShowEditHarvestPicker] = useState(false); const [editQuantity, setEditQuantity] = useState(''); const [editUnit, setEditUnit] = useState('kg'); const [editNotes, setEditNotes] = useState(''); const [editPhotoUri, setEditPhotoUri] = useState(null); const [zoomUri, setZoomUri] = useState(null); const [pendingZoomUri, setPendingZoomUri] = useState(null); const [editErrors, setEditErrors] = useState<{ field?: string; crop?: string; quantity?: string }>( {} ); const selectedField = useMemo( () => fields.find((item) => item.id === selectedFieldId), [fields, selectedFieldId] ); const selectedCrop = useMemo( () => crops.find((item) => item.id === selectedCropId), [crops, selectedCropId] ); const selectedEditField = useMemo( () => fields.find((item) => item.id === editFieldId), [fields, editFieldId] ); const selectedEditCrop = useMemo( () => crops.find((item) => item.id === editCropId), [crops, editCropId] ); useEffect(() => { let isActive = true; async function loadData() { try { await initCoreTables(); const db = await dbPromise; const fieldRows = await db.getAllAsync( 'SELECT id, name FROM fields ORDER BY name ASC;' ); const cropRows = await db.getAllAsync( 'SELECT id, field_id, crop_name FROM crops ORDER BY id DESC;' ); const harvestRows = await db.getAllAsync( `SELECT h.id, h.field_id, h.crop_id, h.harvested_at, h.quantity, h.unit, h.notes, h.photo_uri, f.name as field_name, c.crop_name as crop_name FROM harvests h LEFT JOIN fields f ON f.id = h.field_id LEFT JOIN crops c ON c.id = h.crop_id ORDER BY h.harvested_at DESC;` ); if (!isActive) return; setFields(fieldRows); setCrops(cropRows); setHarvests(harvestRows); setStatus(harvestRows.length === 0 ? t('harvests.empty') : ''); } catch (error) { if (isActive) setStatus(`Error: ${String(error)}`); } } loadData(); return () => { isActive = false; }; }, [t]); async function fetchHarvestsPage() { try { const db = await dbPromise; const harvestRows = await db.getAllAsync( `SELECT h.id, h.field_id, h.crop_id, h.harvested_at, h.quantity, h.unit, h.notes, h.photo_uri, f.name as field_name, c.crop_name as crop_name FROM harvests h LEFT JOIN fields f ON f.id = h.field_id LEFT JOIN crops c ON c.id = h.crop_id ORDER BY h.harvested_at DESC;` ); setHarvests(harvestRows); setStatus(harvestRows.length === 0 ? t('harvests.empty') : ''); } catch (error) { setStatus(`Error: ${String(error)}`); } } useFocusEffect( useCallback(() => { fetchHarvestsPage(); }, [t]) ); useEffect(() => { if (!newModalOpen && !editModalOpen && pendingZoomUri) { const uri = pendingZoomUri; setPendingZoomUri(null); InteractionManager.runAfterInteractions(() => { setTimeout(() => setZoomUri(uri), 150); }); } }, [newModalOpen, editModalOpen, pendingZoomUri]); async function handleSave() { const parsedQty = quantity.trim() ? Number(quantity) : null; const nextErrors: { field?: string; crop?: string; quantity?: string } = {}; if (!selectedFieldId) nextErrors.field = t('harvests.fieldRequired'); if (!selectedCropId) nextErrors.crop = t('harvests.cropRequired'); if (!parsedQty || !Number.isFinite(parsedQty)) nextErrors.quantity = t('harvests.quantityInvalid'); setErrors(nextErrors); if (Object.keys(nextErrors).length > 0) { setStatus(nextErrors.field ?? nextErrors.crop ?? nextErrors.quantity ?? t('harvests.fieldRequired')); return false; } try { const db = await dbPromise; const now = new Date().toISOString(); await db.runAsync( 'INSERT INTO harvests (field_id, crop_id, harvested_at, quantity, unit, notes, photo_uri, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?);', selectedFieldId, selectedCropId, harvestDate.trim() || now, parsedQty, unit.trim() || null, notes.trim() || null, photoUri, now ); setSelectedFieldId(null); setSelectedCropId(null); setHarvestDate(''); setQuantity(''); setUnit('kg'); setNotes(''); setPhotoUri(null); setErrors({}); setStatus(t('harvests.saved')); const harvestRows = await db.getAllAsync( `SELECT h.id, h.field_id, h.crop_id, h.harvested_at, h.quantity, h.unit, h.notes, h.photo_uri, f.name as field_name, c.crop_name as crop_name FROM harvests h LEFT JOIN fields f ON f.id = h.field_id LEFT JOIN crops c ON c.id = h.crop_id ORDER BY h.harvested_at DESC;` ); setHarvests(harvestRows); return true; } catch (error) { setStatus(`Error: ${String(error)}`); return false; } } function startEdit(item: HarvestRow) { router.push(`/harvests/${item.id}`); } function cancelEdit() { setEditingId(null); setEditFieldId(null); setEditCropId(null); setEditHarvestDate(''); setEditQuantity(''); setEditUnit('kg'); setEditNotes(''); setEditPhotoUri(null); setEditErrors({}); setEditModalOpen(false); } async function handleUpdate() { if (!editingId) return; const parsedQty = editQuantity.trim() ? Number(editQuantity) : null; const nextErrors: { field?: string; crop?: string; quantity?: string } = {}; if (!editFieldId) nextErrors.field = t('harvests.fieldRequired'); if (!editCropId) nextErrors.crop = t('harvests.cropRequired'); if (!parsedQty || !Number.isFinite(parsedQty)) nextErrors.quantity = t('harvests.quantityInvalid'); setEditErrors(nextErrors); if (Object.keys(nextErrors).length > 0) { setStatus(nextErrors.field ?? nextErrors.crop ?? nextErrors.quantity ?? t('harvests.fieldRequired')); return; } try { const db = await dbPromise; const now = new Date().toISOString(); await db.runAsync( 'UPDATE harvests SET field_id = ?, crop_id = ?, harvested_at = ?, quantity = ?, unit = ?, notes = ?, photo_uri = ? WHERE id = ?;', editFieldId, editCropId, editHarvestDate.trim() || now, parsedQty, editUnit.trim() || null, editNotes.trim() || null, editPhotoUri, editingId ); setStatus(t('harvests.saved')); setEditModalOpen(false); setEditingId(null); const harvestRows = await db.getAllAsync( `SELECT h.id, h.field_id, h.crop_id, h.harvested_at, h.quantity, h.unit, h.notes, h.photo_uri, f.name as field_name, c.crop_name as crop_name FROM harvests h LEFT JOIN fields f ON f.id = h.field_id LEFT JOIN crops c ON c.id = h.crop_id ORDER BY h.harvested_at DESC;` ); setHarvests(harvestRows); } catch (error) { setStatus(`Error: ${String(error)}`); } } function confirmDelete(id: number) { Alert.alert(t('harvests.deleteTitle'), t('harvests.deleteMessage'), [ { text: t('harvests.cancel'), style: 'cancel' }, { text: t('harvests.delete'), style: 'destructive', onPress: () => handleDelete(id) }, ]); } async function handleDelete(id: number) { try { const db = await dbPromise; await db.runAsync('DELETE FROM harvests WHERE id = ?;', id); const harvestRows = await db.getAllAsync( `SELECT h.id, h.field_id, h.crop_id, h.harvested_at, h.quantity, h.unit, h.notes, h.photo_uri, f.name as field_name, c.crop_name as crop_name FROM harvests h LEFT JOIN fields f ON f.id = h.field_id LEFT JOIN crops c ON c.id = h.crop_id ORDER BY h.harvested_at DESC;` ); setHarvests(harvestRows); setStatus(harvestRows.length === 0 ? t('harvests.empty') : ''); } catch (error) { setStatus(`Error: ${String(error)}`); } } const inputStyle = [ styles.input, { borderColor: palette.border, backgroundColor: palette.input, color: palette.text }, ]; return ( <> String(item.id)} renderItem={({ item }) => ( startEdit(item)}> {item.crop_name || t('harvests.untitled')} confirmDelete(item.id)} accessibilityLabel={t('harvests.delete')} variant="danger" /> {item.field_name || t('harvests.noField')} {item.harvested_at ? ( {formatDate(item.harvested_at)} ) : null} {item.quantity !== null ? ( {item.quantity} {item.unit || t('harvests.unitPlaceholder')} ) : null} {normalizeMediaUri(item.photo_uri) ? ( isVideoUri(normalizeMediaUri(item.photo_uri) as string) ? ( )} ItemSeparatorComponent={() => } ListHeaderComponent={ {t('harvests.title')} {status ? ( {status} ) : null} router.push('/harvests/new')}> {t('harvests.new')} } ListFooterComponent={} /> setFieldModalOpen(false)}> {t('harvests.selectField')} String(item.id)} renderItem={({ item }) => ( { if (fieldModalTarget === 'edit') { setEditFieldId(item.id); setEditCropId(null); setEditErrors((prev) => ({ ...prev, field: undefined })); setEditModalOpen(true); } else { setSelectedFieldId(item.id); setSelectedCropId(null); setErrors((prev) => ({ ...prev, field: undefined })); setNewModalOpen(true); } setFieldModalOpen(false); }} style={styles.modalItem}> {item.name || t('harvests.untitled')} )} /> setCropModalOpen(false)}> {t('harvests.selectCrop')} { const targetField = cropModalTarget === 'edit' ? editFieldId : selectedFieldId; return !targetField || item.field_id === targetField; })} keyExtractor={(item) => String(item.id)} renderItem={({ item }) => ( { if (cropModalTarget === 'edit') { setEditCropId(item.id); setEditErrors((prev) => ({ ...prev, crop: undefined })); setEditModalOpen(true); } else { setSelectedCropId(item.id); setErrors((prev) => ({ ...prev, crop: undefined })); setNewModalOpen(true); } setCropModalOpen(false); }} style={styles.modalItem}> {item.crop_name || t('harvests.untitled')} )} ListEmptyComponent={ {t('harvests.noCrop')} } /> setNewModalOpen(false)} /> item.key} contentContainerStyle={styles.sheetListContent} renderItem={() => ( {t('harvests.new')} {t('harvests.field')} * { setFieldModalTarget('new'); setNewModalOpen(false); setFieldModalOpen(true); }} variant="secondary" /> {errors.field ? ( {errors.field} ) : null} {t('harvests.crop')} * { setCropModalTarget('new'); setNewModalOpen(false); setCropModalOpen(true); }} variant="secondary" /> {errors.crop ? ( {errors.crop} ) : null} {t('harvests.date')} setShowHarvestPicker(true)} style={styles.dateInput}> {harvestDate ? formatDateLabel(harvestDate) : t('harvests.datePlaceholder')} {showHarvestPicker ? ( <> {Platform.OS === 'ios' ? ( { setHarvestDate(toDateOnly(new Date())); setShowHarvestPicker(false); }} variant="secondary" /> setShowHarvestPicker(false)} variant="secondary" /> ) : null} { if (date) setHarvestDate(toDateOnly(date)); if (Platform.OS !== 'ios') setShowHarvestPicker(false); }} /> ) : null} {t('harvests.quantity')} * { setQuantity(value); if (errors.quantity) { setErrors((prev) => ({ ...prev, quantity: undefined })); } }} placeholder={t('harvests.quantityPlaceholder')} style={inputStyle} keyboardType="decimal-pad" /> {errors.quantity ? ( {errors.quantity} ) : null} {t('harvests.unit')} {unitPresets.map((preset) => { const label = t(`units.${preset.key}`); const normalized = unit.trim().toLowerCase(); const isActive = label.toLowerCase() === normalized || preset.value.toLowerCase() === normalized; return ( setUnit(label)} style={[styles.unitChip, isActive && styles.unitChipActive]}> {label} ); })} {t('harvests.notes')} {t('harvests.addMedia')} {normalizeMediaUri(photoUri) ? ( isVideoUri(normalizeMediaUri(photoUri) as string) ? ( item.key} contentContainerStyle={styles.sheetListContent} renderItem={() => ( {t('harvests.edit')} {t('harvests.field')} * { setFieldModalTarget('edit'); setEditModalOpen(false); setFieldModalOpen(true); }} variant="secondary" /> {editErrors.field ? ( {editErrors.field} ) : null} {t('harvests.crop')} * { setCropModalTarget('edit'); setEditModalOpen(false); setCropModalOpen(true); }} variant="secondary" /> {editErrors.crop ? ( {editErrors.crop} ) : null} {t('harvests.date')} setShowEditHarvestPicker(true)} style={styles.dateInput}> {editHarvestDate ? formatDateLabel(editHarvestDate) : t('harvests.datePlaceholder')} {showEditHarvestPicker ? ( <> {Platform.OS === 'ios' ? ( { setEditHarvestDate(toDateOnly(new Date())); setShowEditHarvestPicker(false); }} variant="secondary" /> setShowEditHarvestPicker(false)} variant="secondary" /> ) : null} { if (date) setEditHarvestDate(toDateOnly(date)); if (Platform.OS !== 'ios') setShowEditHarvestPicker(false); }} /> ) : null} {t('harvests.quantity')} * { setEditQuantity(value); if (editErrors.quantity) { setEditErrors((prev) => ({ ...prev, quantity: undefined })); } }} placeholder={t('harvests.quantityPlaceholder')} style={inputStyle} keyboardType="decimal-pad" /> {editErrors.quantity ? ( {editErrors.quantity} ) : null} {t('harvests.unit')} {unitPresets.map((preset) => { const label = t(`units.${preset.key}`); const normalized = editUnit.trim().toLowerCase(); const isActive = label.toLowerCase() === normalized || preset.value.toLowerCase() === normalized; return ( setEditUnit(label)} style={[styles.unitChip, isActive && styles.unitChipActive]}> {label} ); })} {t('harvests.notes')} {t('harvests.addMedia')} {normalizeMediaUri(editPhotoUri) ? ( isVideoUri(normalizeMediaUri(editPhotoUri) as string) ? ( setZoomUri(null)} /> ); } function formatDate(value: string) { try { return new Date(value).toLocaleString(); } catch { return value; } } function formatDateLabel(value: string) { try { return new Date(value).toISOString().slice(0, 10); } catch { return value; } } function toDateOnly(date: Date) { return date.toISOString().slice(0, 10); } async function handlePickPhoto(setter: (value: string | null) => void) { const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: getMediaTypes(), quality: 1, }); if (result.canceled) return; const asset = result.assets[0]; setter(asset.uri); } async function handleTakePhoto( setter: (value: string | null) => void, onError?: (msg: string) => void ) { try { const permission = await ImagePicker.requestCameraPermissionsAsync(); if (!permission.granted) { onError?.('cameraDenied'); return; } const result = await ImagePicker.launchCameraAsync({ mediaTypes: getMediaTypes(), quality: 1, }); if (result.canceled) return; const asset = result.assets[0]; setter(asset.uri); } catch { onError?.('cameraError'); } } function getMediaTypes() { const mediaType = (ImagePicker as { MediaType?: { Image?: unknown; Images?: unknown; Video?: unknown; Videos?: unknown }; }).MediaType; const imageType = mediaType?.Image ?? mediaType?.Images; const videoType = mediaType?.Video ?? mediaType?.Videos; if (imageType && videoType) { return [imageType, videoType]; } return imageType ?? videoType ?? ['images', 'videos']; } function isVideoUri(uri: string) { return /\.(mp4|mov|m4v|webm|avi|mkv)(\?.*)?$/i.test(uri); } function normalizeMediaUri(uri?: string | null) { if (typeof uri !== 'string') return null; const trimmed = uri.trim(); return trimmed ? trimmed : null; } const styles = StyleSheet.create({ hero: { backgroundColor: '#E8E6DA', aspectRatio: 16 / 9, width: '100%', }, heroImage: { width: '100%', height: '100%', }, titleContainer: { gap: 8, paddingHorizontal: 16, paddingVertical: 12, }, section: { gap: 8, marginBottom: 16, paddingHorizontal: 16, }, newButton: { flexDirection: 'row', alignItems: 'center', gap: 8, borderRadius: 10, borderWidth: 1, borderColor: '#B9B9B9', paddingHorizontal: 12, paddingVertical: 10, alignSelf: 'flex-start', }, newButtonText: { fontSize: 15, fontWeight: '600', }, card: { borderRadius: 12, borderWidth: 1, borderColor: '#C6C6C6', padding: 12, marginHorizontal: 16, gap: 6, backgroundColor: '#FFFFFF', }, cardHeader: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 8, }, meta: { opacity: 0.7, }, separator: { height: 12, }, footer: { height: 24, }, modalOverlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.3)', justifyContent: 'center', padding: 16, }, modalCard: { borderRadius: 12, borderWidth: 1, borderColor: '#C6C6C6', padding: 16, backgroundColor: '#FFFFFF', gap: 8, maxHeight: '70%', }, modalItem: { paddingVertical: 8, }, input: { borderRadius: 10, borderWidth: 1, borderColor: '#B9B9B9', paddingHorizontal: 12, paddingVertical: 10, fontSize: 15, }, dateInput: { borderRadius: 10, borderWidth: 1, borderColor: '#B9B9B9', paddingHorizontal: 12, paddingVertical: 10, }, dateValue: { fontSize: 15, opacity: 0.9, }, pickerRow: { flexDirection: 'row', gap: 8, }, modalActions: { flexDirection: 'row', justifyContent: 'space-between', gap: 12, }, sheetOverlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.3)', justifyContent: 'flex-end', }, sheetBackdrop: { ...StyleSheet.absoluteFillObject, }, sheet: { borderTopLeftRadius: 16, borderTopRightRadius: 16, borderWidth: 1, borderColor: '#C6C6C6', padding: 16, backgroundColor: '#FFFFFF', gap: 10, maxHeight: '85%', }, sheetContent: { gap: 10, }, sheetListContent: { paddingBottom: 80, }, sheetFooter: { height: 24, }, keyboardAvoid: { width: '100%', flex: 1, justifyContent: 'flex-end', }, photoRow: { flexDirection: 'row', gap: 12, }, photoPreview: { width: '100%', height: 200, borderRadius: 12, }, videoPreview: { width: '100%', height: 200, borderRadius: 12, backgroundColor: '#1C1C1C', }, photoPlaceholder: { opacity: 0.6, }, unitRow: { flexDirection: 'row', flexWrap: 'wrap', gap: 8, }, unitChip: { borderRadius: 999, borderWidth: 1, borderColor: '#C6C6C6', paddingHorizontal: 10, paddingVertical: 4, }, unitChipActive: { borderColor: '#2F7D4F', backgroundColor: '#E7F3EA', }, unitText: { fontSize: 12, }, unitTextActive: { fontSize: 12, color: '#2F7D4F', fontWeight: '600', }, requiredMark: { color: '#C0392B', fontWeight: '700', }, errorText: { color: '#C0392B', fontSize: 12, }, });