'use client'; import React, { useState, useEffect } from 'react'; import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'; import { Calendar, Plus, GlassWater, Loader2, ChevronRight, Users, Check, Trash2, ChevronDown, ChevronUp } from 'lucide-react'; import Link from 'next/link'; import AvatarStack from './AvatarStack'; import { deleteSession } from '@/services/delete-session'; import { useI18n } from '@/i18n/I18nContext'; import { useSession } from '@/context/SessionContext'; interface Session { id: string; name: string; scheduled_at: string; participant_count?: number; whisky_count?: number; participants?: string[]; } export default function SessionList() { const { t, locale } = useI18n(); const supabase = createClientComponentClient(); const [sessions, setSessions] = useState([]); const [isLoading, setIsLoading] = useState(true); const [isCreating, setIsCreating] = useState(false); const [isDeleting, setIsDeleting] = useState(null); const [isCollapsed, setIsCollapsed] = useState(() => { if (typeof window !== 'undefined') { return localStorage.getItem('whisky-sessions-collapsed') === 'true'; } return false; }); const [newName, setNewName] = useState(''); const { activeSession, setActiveSession } = useSession(); useEffect(() => { fetchSessions(); }, []); const fetchSessions = async () => { const { data, error } = await supabase .from('tasting_sessions') .select(` *, session_participants ( count, buddies (name) ), tastings (count) `) .order('scheduled_at', { ascending: false }); if (error) { console.error('Error fetching sessions:', error); // Fallback: try without tastings join if relationship is missing const { data: fallbackData, error: fallbackError } = await supabase .from('tasting_sessions') .select(` *, session_participants (count) `) .order('scheduled_at', { ascending: false }); if (fallbackError) { console.error('Error fetching sessions fallback:', fallbackError); } else { setSessions(fallbackData.map(s => ({ ...s, participant_count: s.session_participants[0]?.count || 0, participants: (s.session_participants as any[])?.filter(p => p.buddies).map(p => p.buddies.name) || [], whisky_count: 0 })) || []); } } else { setSessions(data.map(s => ({ ...s, participant_count: s.session_participants[0]?.count || 0, participants: (s.session_participants as any[])?.filter(p => p.buddies).map(p => p.buddies.name) || [], whisky_count: s.tastings[0]?.count || 0 })) || []); } setIsLoading(false); }; const handleToggleCollapse = () => { const nextState = !isCollapsed; setIsCollapsed(nextState); localStorage.setItem('whisky-sessions-collapsed', String(nextState)); }; const handleCreateSession = async (e: React.FormEvent) => { e.preventDefault(); if (!newName.trim()) return; setIsCreating(true); const { data: { user } } = await supabase.auth.getUser(); if (!user) return; const { data, error } = await supabase .from('tasting_sessions') .insert([{ name: newName.trim(), user_id: user.id }]) .select() .single(); if (error) { console.error('Error creating session:', error); } else { setSessions(prev => [data, ...prev]); setNewName(''); setActiveSession({ id: data.id, name: data.name }); } setIsCreating(false); }; const handleDeleteSession = async (e: React.MouseEvent, sessionId: string) => { e.preventDefault(); e.stopPropagation(); if (!confirm('Möchtest du diese Session wirklich löschen? Alle Verknüpfungen gehen verloren.')) return; setIsDeleting(sessionId); const result = await deleteSession(sessionId); if (result.success) { setSessions(prev => prev.filter(s => s.id !== sessionId)); if (activeSession?.id === sessionId) { setActiveSession(null); } } else { alert(result.error); } setIsDeleting(null); }; return (

{t('session.title')} {!isCollapsed && sessions.length > 0 && ( ({sessions.length}) )}

{!isCollapsed && ( <>
setNewName(e.target.value)} placeholder={t('session.sessionName')} className="flex-1 bg-zinc-50 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-xl px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-amber-500/50" />
{isLoading ? (
) : sessions.length === 0 ? (
{t('session.noSessions')}
) : (
{sessions.map((session) => (
{session.name}
{new Date(session.scheduled_at).toLocaleDateString(locale === 'de' ? 'de-DE' : 'en-US')} {session.whisky_count! > 0 && ( {session.whisky_count} Whiskys )}
{session.participants && session.participants.length > 0 && (
)}
{activeSession?.id !== session.id ? ( ) : (
)}
))}
)} )} {isCollapsed && sessions.length > 0 && (
{sessions.slice(0, 3).map((s, i) => (
{s.name[0].toUpperCase()}
))} {sessions.length > 3 && (
+{sessions.length - 3}
)}
{sessions.length} Sessions
)}
); }