import { defaultStyles } from '@/constants/defaultStyles'; import { supabase } from '@/lib/supabase'; import { router, Stack, useFocusEffect, useLocalSearchParams } from 'expo-router'; import { useCallback, useState } from 'react'; import { ActivityIndicator, Alert, Button, Keyboard, KeyboardAvoidingView, Platform, Pressable, Text, TextInput, TouchableWithoutFeedback, View } from 'react-native'; type Subject = { sId: string; title: string; description: string; isActive: boolean; lastChanged: string; uId: string; } export default function EditSubject() { const { sId } = useLocalSearchParams<{ sId: string }>(); const [subject, SetSubject] = useState(null) const [isSaving, SetIsSaving] = useState(false); const GetSubject = async (sId: string) => { const { data, error } = await supabase.from("subjects").select("*").eq("sId", sId).single(); if (error) { Alert.alert("Subject could not be fetched, please try again"); return; } SetSubject(data ?? null); } useFocusEffect( useCallback(() => { if (sId) { GetSubject(sId); } }, [sId]) ); const EditSubject = async () => { if (!subject) return; if(subject.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("subjects").update({ title: subject.title, description: subject.description, isActive: subject.isActive, lastChanged: new Date().toISOString(), uId: data.user.id, }).eq("sId", sId); SetIsSaving(false); if (dbError) { Alert.alert("Subject could not be edited, please try again"); return; } Alert.alert("Subject successfully edited!"); router.back(); } return ( {!subject && ( Subject not found )} {subject && ( Edit Subject SetSubject(prev => prev ? { ...prev, title: text } : prev)} /> SetSubject(prev => prev ? { ...prev, description: text } : prev)} /> SetSubject(prev => prev ? { ...prev, isActive: !prev.isActive } : prev)} style={defaultStyles.checkboxContainer} > {subject.isActive && } {subject.isActive ? 'Active' : 'inactive'}