import { SUBJECT_COLORS, type SubjectColor } from '@/lib/subjectColors'; import { supabase } from '@/lib/supabase'; import { Subject } from '@/lib/types'; import { Session } from '@supabase/supabase-js'; import { router, Stack, useFocusEffect } from 'expo-router'; import { useCallback, useEffect, useState } from 'react'; import { ActivityIndicator, Alert, Pressable, ScrollView, Text, View, } from 'react-native'; export default function Subjects() { const [subjects, SetSubjects] = useState([]); const [session, SetSession] = useState(null); const [isLoading, SetIsLoading] = useState(true); const activeSubjects = subjects.filter((subject) => subject.isActive); const inactiveSubjects = subjects.filter((subject) => !subject.isActive); useEffect(() => { supabase.auth.getSession().then(({ data }) => { SetSession(data.session ?? null); }); const { data: sub } = supabase.auth.onAuthStateChange( (_event, newSession) => { SetSession(newSession); } ); return () => sub.subscription.unsubscribe(); }, []); const GetSubjects = async () => { if (!session?.user.id) { SetIsLoading(false); return; } SetIsLoading(true); const { data, error } = await supabase .from('subjects') .select('*') .eq('uId', session.user.id) .order('lastChanged', { ascending: false }); if (error) { Alert.alert('Subjects could not be fetched, please try again'); SetIsLoading(false); return; } SetSubjects((data as Subject[]) ?? []); SetIsLoading(false); }; useFocusEffect( useCallback(() => { if (session) { GetSubjects(); } }, [session]) ); const RenderSubjectCard = (subject: Subject) => { const colorKey: SubjectColor = subject.color ?? 'slate'; const colorSet = SUBJECT_COLORS[colorKey]; const firstLetter = subject.title?.trim().charAt(0).toUpperCase() || '?'; return ( router.push({ pathname: '/subject/viewDetailsSubject', params: { sId: subject.sId }, }) } > {firstLetter} {subject.title} {subject.description || 'No description added.'} {subject.isActive ? 'Active' : 'Inactive'} ); }; return ( ( await supabase.auth.signOut()} > Logout ), }} /> {isLoading ? ( Loading subjects... ) : subjects.length === 0 ? ( No subjects yet Create your first subject to get started. ) : ( Active Subjects {activeSubjects.length} {activeSubjects.length === 0 ? ( No active subjects Subjects with ongoing work will show up here. ) : ( activeSubjects.map(RenderSubjectCard) )} Inactive Subjects {inactiveSubjects.length} {inactiveSubjects.length === 0 ? ( No inactive subjects Completed or paused subjects will show up here. ) : ( inactiveSubjects.map(RenderSubjectCard) )} )} router.push('/subject/upsertSubject')} > Create Subject ); }