import { supabase } from '@/lib/supabase'; import { router, Stack, useFocusEffect, useLocalSearchParams, } from 'expo-router'; import { useCallback, useState } from 'react'; import { ActivityIndicator, Alert, Keyboard, KeyboardAvoidingView, Platform, Pressable, ScrollView, Text, TextInput, TouchableWithoutFeedback, View, } from 'react-native'; export default function EditTask() { const { taskId } = useLocalSearchParams<{ taskId?: string }>(); const [title, setTitle] = useState(''); const [description, setDescription] = useState(''); const [deadline, setDeadline] = useState(''); const [isCompleted, setIsCompleted] = useState(false); const [isLoading, setIsLoading] = useState(false); const [isSaving, setIsSaving] = useState(false); useFocusEffect( useCallback(() => { const getTask = async () => { if (!taskId) return; setIsLoading(true); try { const { data, error } = await supabase .from('tasks') .select('*') .eq('tId', taskId) .single(); if (error || !data) { Alert.alert('Task not found'); router.back(); return; } setTitle(data.title ?? ''); setDescription(data.description ?? ''); setDeadline(data.deadline ?? ''); setIsCompleted(Boolean(data.isCompleted)); } finally { setIsLoading(false); } }; getTask(); }, [taskId]) ); const handleSaveTask = async () => { if (!title.trim() || !description.trim() || !deadline.trim()) { Alert.alert('All fields are required!'); return; } setIsSaving(true); try { const { data: userData, error: userError } = await supabase.auth.getUser(); if (userError || !userData.user) { router.replace('../createUser'); return; } const { error: dbError } = await supabase .from('tasks') .update({ title: title.trim(), description: description.trim(), isCompleted, lastChanged: new Date().toISOString(), deadline: deadline.trim(), uId: userData.user.id, }) .eq('tId', taskId); if (dbError) { Alert.alert('Task could not be edited, please try again'); return; } Alert.alert('Task successfully edited!'); router.back(); } finally { setIsSaving(false); } }; return ( <> Edit Task Update the details for this task. {isLoading ? ( Loading task... ) : ( <> Title Description Deadline setIsCompleted((current) => !current)} > {isCompleted && ( )} {isCompleted ? 'Completed' : 'Not completed'} {isSaving ? 'Saving...' : 'Save Changes'} {isSaving && ( )} router.back()} disabled={isSaving} > Cancel )} ); }