import { CheckAssignmentCompletion } from '@/lib/progress'; import { supabase } from '@/lib/supabase'; import type { Task } from '@/lib/types'; 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 { tId } = useLocalSearchParams<{ tId: string }>(); const [task, SetTask] = useState(null); const [isSaving, SetIsSaving] = useState(false); const GetTask = async (tId: string) => { const { data, error } = await supabase.from("tasks").select("*").eq("tId", tId).single(); if (error) { Alert.alert("Task could not be fetched, please try again"); return; } SetTask(data ?? null); } useFocusEffect( useCallback(() => { if (tId) { GetTask(tId); } }, [tId]) ); const EditTask = async () => { if (!task) return; if(task.title.trim() === '') { Alert.alert("Title is required!"); return; } const { data, error: userError } = await supabase.auth.getUser(); if(userError || !data.user) { router.replace("../createUser"); return; } SetIsSaving(true); const { error: dbError } = await supabase.from("tasks").update({ title: task.title, description: task.description, isCompleted: task.isCompleted, lastChanged: new Date().toISOString(), uId: data.user.id, aId: task.aId, }).eq("tId", tId); SetIsSaving(false); if (dbError) { Alert.alert("Task could not be edited, please try again"); return; } if (task.aId) { try { await CheckAssignmentCompletion(task.aId); } catch { Alert.alert("Failed to update assignment completion state"); } } Alert.alert("Task successfully edited!"); router.back(); }; const inputClassName = 'rounded-2xl border border-app-border bg-app-subtle px-4 py-3 text-base text-text-main'; const labelClassName = 'mb-2 text-sm font-semibold text-text-secondary'; return ( <> {!task ? ( Task not found The task could not be loaded. router.back()} > Go back ) : ( Edit Task Update the task details and completion state. Title SetTask((prev) => (prev ? { ...prev, title: text } : prev)) } returnKeyType="next" /> Description SetTask((prev) => prev ? { ...prev, description: text } : prev ) } multiline textAlignVertical="top" /> SetTask((prev) => prev ? { ...prev, isCompleted: !prev.isCompleted } : prev ) } disabled={isSaving} className={`mb-6 flex-row items-center rounded-2xl border p-4 ${ task.isCompleted ? 'border-accent bg-accent-soft' : 'border-app-border bg-app-subtle' }`} > {task.isCompleted && ( )} Mark as completed You can change this again later. {isSaving ? ( Saving... ) : ( Save Changes )} router.back()} disabled={isSaving} > Cancel )} ); }