import { defaultStyles } from '@/constants/defaultStyles'; import * as AsyncStorage from '@/lib/asyncStorage'; import { supabase } from '@/lib/supabase'; import * as Notifications from 'expo-notifications'; import { router, Stack, useLocalSearchParams } from 'expo-router'; import { useState } from 'react'; import { ActivityIndicator, Alert, Keyboard, KeyboardAvoidingView, Platform, Pressable, ScrollView, Text, TextInput, TouchableWithoutFeedback, View, } from 'react-native'; export default function CreateAssignment() { const sId = (useLocalSearchParams().sId as string) ?? null; const [title, SetTitle] = useState(''); const [description, SetDescription] = useState(''); const [deadline, SetDeadline] = useState(''); const [isCompleted, SetIsCompleted] = useState(false); const [isSaving, SetIsSaving] = useState(false); const ScheduleDeadlineReminder = async (aId: string, title: string, deadline: string) => { const dl = new Date(deadline); if (isNaN(dl.getTime())) return null; const deadlineReminder = new Date(dl.getTime() - 24 * 60 * 60 * 1000); if (deadlineReminder <= new Date()) return null; const nId = await Notifications.scheduleNotificationAsync({ content: { title: 'Assignment deadline coming up', body: `${title} is due in 24 hours.`, data: { aId }, }, trigger: { type: Notifications.SchedulableTriggerInputTypes.DATE, date: deadlineReminder, }, }); return nId; } const CreateAssignment = async () => { if (title.trim() === '') { Alert.alert('Title is required!'); return; } const { data: userData, error: userError } = await supabase.auth.getUser(); if (userError || !userData.user) { router.replace('../createUser'); return; } SetIsSaving(true); const { data: assignmentData, error: dbError } = await supabase.from('assignments').insert({ title: title.trim(), description: description.trim(), deadline: deadline.trim(), isCompleted, lastChanged: new Date().toISOString(), uId: userData.user.id, sId, }) .select() .single(); if (dbError) { SetIsSaving(false); Alert.alert('Assignment could not be created, please try again'); return; } Alert.alert('Assignment successfully created!'); if (!isCompleted && assignmentData) { const nId = await ScheduleDeadlineReminder(assignmentData.aId, assignmentData.title, assignmentData.deadline); if (nId) { await AsyncStorage.SaveAssignmentNotificationId(assignmentData.aId, nId); } } SetTitle(''); SetDescription(''); SetDeadline(''); SetIsCompleted(false); SetIsSaving(false); 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 ( <> Create Assignment Add a new assignment to keep your subject organized. Title Description Deadline SetIsCompleted((current) => !current)} disabled={isSaving} > {isCompleted && ( )} Mark as completed You can change this later. {isSaving ? ( Creating... ) : ( Create Assignment )} router.back()} disabled={isSaving} > Cancel ); }