import { useEffect, useMemo, useState } from 'react'; import { supabase } from '../lib/supabase'; import { evaluateSessionFeedback, getAllContacts, getAllSessionSpeakers, getActiveEvent, getSessions, getSlots, removeSessionMaterial, sessionMaterialUrl, setSessionSpeakers, uploadSessionMaterial, } from '../lib/api'; import type { Contact, Event, Session, SessionSpeaker, Slot, SlotType } from '../lib/types'; import { useToast } from '../context/ToastContext'; import { Empty, Modal, Spinner, TypeBadge } from '../components/ui'; const SLOT_TYPES: SlotType[] = ['session', 'service_session']; export function Schedule() { const { push } = useToast(); const [event, setEvent] = useState(null); const [loaded, setLoaded] = useState(false); const [slots, setSlots] = useState([]); const [sessions, setSessions] = useState([]); const [speakers, setSpeakers] = useState([]); const [contacts, setContacts] = useState([]); const [error, setError] = useState(null); const [slotModal, setSlotModal] = useState<{ slot: Slot | null } | null>(null); const [sessModal, setSessModal] = useState<{ session: Session | null; slotId: number } | null>(null); const [busy, setBusy] = useState(false); async function load() { try { const ev = await getActiveEvent(); setEvent(ev); if (ev) { const [s, ss, sp, c] = await Promise.all([ getSlots(ev.id), getSessions(ev.id), getAllSessionSpeakers(), getAllContacts(), ]); setSlots(s); setSessions(ss); const ids = new Set(ss.map((x) => x.id)); setSpeakers(sp.filter((x) => ids.has(x.session_id))); setContacts(c); } setLoaded(true); } catch (e) { setError(e instanceof Error ? e.message : 'Failed to load'); } } useEffect(() => { load(); }, []); const speakersFor = useMemo(() => { const m = new Map(); for (const sp of speakers) { const arr = m.get(sp.session_id) ?? []; arr.push(sp.contact_email); m.set(sp.session_id, arr); } return m; }, [speakers]); const nameOf = (email: string) => contacts.find((c) => c.email === email)?.full_name ?? email; async function deleteSlot(slot: Slot) { if (!confirm(`Delete "${slot.name}" and all its sessions?`)) return; setBusy(true); try { const { error: err } = await supabase.from('slots').delete().eq('id', slot.id); if (err) throw err; await load(); push('success', `Deleted ${slot.name}`); } catch (e) { push('error', e instanceof Error ? e.message : 'Delete failed'); } finally { setBusy(false); } } async function deleteSession(sess: Session) { if (!confirm(`Delete session "${sess.title}"?`)) return; setBusy(true); try { const { error: err } = await supabase.from('sessions').delete().eq('id', sess.id); if (err) throw err; await load(); push('success', `Deleted ${sess.title}`); } catch (e) { push('error', e instanceof Error ? e.message : 'Delete failed'); } finally { setBusy(false); } } async function doEvaluate(sess: Session) { setBusy(true); try { await evaluateSessionFeedback(sess.id); await load(); push('success', `AI feedback evaluated for ${sess.title}`); } catch (e) { push('error', e instanceof Error ? e.message : 'Evaluation failed'); } finally { setBusy(false); } } if (error) return ; if (!loaded) return (
); if (!event) { return (

Schedule

Slots, sessions, speakers, and materials.
); } return (

Schedule

{event.name} · {slots.length} slots · {sessions.length} sessions.
{slots.map((slot) => { const slotSessions = sessions.filter((s) => s.slot_id === slot.id); return (
{slot.name}
{fmtDate(slot.slot_date)} · {fmtTime(slot.start_time)}–{fmtTime(slot.end_time)}
{slotSessions.length === 0 ? (
No sessions in this slot.
) : (
{slotSessions.map((s) => { const spk = (speakersFor.get(s.id) ?? []).map(nameOf).join(', '); return (
{s.title}
{[s.room, spk || 'no speakers', s.capacity ? `cap ${s.capacity}` : null].filter(Boolean).join(' · ')}
{s.average_feedback != null && ⭐ {s.average_feedback.toFixed(1)}} · {s.material_path ? '📎 material submitted' : '⬜ material not submitted'} {s.ai_generated_feedback && ( · 🤖 {s.ai_generated_feedback} )}
{s.ai_generated_feedback === 'Pending AI Evaluation' && ( )}
); })}
)}
); })}
{slotModal && ( setSlotModal(null)} onSaved={async (msg) => { setSlotModal(null); await load(); push('success', msg); }} /> )} {sessModal && ( setSessModal(null)} onSaved={async (msg) => { setSessModal(null); await load(); push('success', msg); }} /> )}
); } function SlotModal({ slot, eventId, onClose, onSaved, }: { slot: Slot | null; eventId: string; onClose: () => void; onSaved: (msg: string) => void; }) { const [name, setName] = useState(slot?.name ?? ''); const [type, setType] = useState(slot?.type ?? 'session'); const [date, setDate] = useState(slot ? slot.slot_date.slice(0, 10) : ''); const [start, setStart] = useState(slot ? slot.start_time.slice(0, 5) : '09:00'); const [end, setEnd] = useState(slot ? slot.end_time.slice(0, 5) : '10:00'); const [busy, setBusy] = useState(false); async function save() { if (!name.trim() || !date) return; setBusy(true); try { const payload = { name: name.trim(), type, slot_date: date, start_time: start, end_time: end, event_id: eventId }; if (slot) { const { error: err } = await supabase.from('slots').update(payload).eq('id', slot.id); if (err) throw err; } else { const { error: err } = await supabase.from('slots').insert(payload); if (err) throw err; } onSaved(slot ? 'Slot updated' : 'Slot created'); } catch (e) { onSaved(e instanceof Error ? e.message : 'Save failed'); } finally { setBusy(false); } } return ( } >
setName(e.target.value)} placeholder="e.g. Morning keynote" />
setDate(e.target.value)} />
setStart(e.target.value)} />
setEnd(e.target.value)} />
); } function SessionModal({ session, slotId, eventId, contacts, currentSpeakers, onClose, onSaved, }: { session: Session | null; slotId: number; eventId: string; contacts: Contact[]; currentSpeakers: string[]; onClose: () => void; onSaved: (msg: string) => void; }) { const [title, setTitle] = useState(session?.title ?? ''); const [room, setRoom] = useState(session?.room ?? ''); const [capacity, setCapacity] = useState(session?.capacity?.toString() ?? ''); const [description, setDescription] = useState(session?.description ?? ''); const [speakerEmails, setSpeakerEmails] = useState(currentSpeakers); const [material, setMaterial] = useState(null); const [busy, setBusy] = useState(false); async function save() { if (!title.trim()) return; setBusy(true); try { const payload = { title: title.trim(), room: room.trim() || null, capacity: capacity ? parseInt(capacity, 10) : null, description: description.trim() || null, slot_id: slotId, event_id: eventId, }; let sessionId = session?.id; if (session) { const { error: err } = await supabase.from('sessions').update(payload).eq('id', session.id); if (err) throw err; } else { const { data: ins, error: err } = await supabase.from('sessions').insert(payload).select().single(); if (err) throw err; sessionId = (ins as Session).id; } // Speakers (a session must keep >= 1 speaker). if (sessionId && speakerEmails.length > 0) { await setSessionSpeakers(sessionId, speakerEmails); } // Material upload (if a new file was chosen). if (sessionId && material) { await uploadSessionMaterial(sessionId, material); } onSaved(session ? 'Session updated' : 'Session created'); } catch (e) { onSaved(e instanceof Error ? e.message : 'Save failed'); } finally { setBusy(false); } } function toggleSpeaker(email: string) { setSpeakerEmails((prev) => prev.includes(email) ? prev.filter((x) => x !== email) : [...prev, email], ); } return ( } >
setTitle(e.target.value)} placeholder="e.g. The future of networking" />
setRoom(e.target.value)} placeholder="—" />
setCapacity(e.target.value)} placeholder="—" />