'use client';

import React, { useState, useEffect } from 'react';
import { createClient } from '@/lib/supabase/client';
import { Calendar, Plus, GlassWater, Loader2, ChevronRight, Users, Check, Trash2, ChevronDown, ChevronUp, Play, Sparkles } 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';
import { useAuth } from '@/context/AuthContext';

interface Session {
    id: string;
    name: string;
    scheduled_at: string;
    ended_at?: string;
    participant_count?: number;
    whisky_count?: number;
    participants?: string[];
}

export default function SessionList() {
    const { t, locale } = useI18n();
    const supabase = createClient();
    const [sessions, setSessions] = useState<Session[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [isCreating, setIsCreating] = useState(false);
    const [isDeleting, setIsDeleting] = useState<string | null>(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();
    const { user, isLoading: isAuthLoading } = useAuth();

    useEffect(() => {
        if (!isAuthLoading && user) {
            fetchSessions();
        }
    }, [user, isAuthLoading]);

    const fetchSessions = async () => {
        const { data, error } = await supabase
            .from('tasting_sessions')
            .select(`
                *,
                session_participants (
                    buddies (name)
                ),
                tastings (count)
            `)
            .order('scheduled_at', { ascending: false });

        if (error) {
            console.error('Error fetching sessions:', error);
            // Fallback: try without tastings join
            const { data: fallbackData, error: fallbackError } = await supabase
                .from('tasting_sessions')
                .select(`
                    *,
                    session_participants (buddies(name))
                `)
                .order('scheduled_at', { ascending: false });

            if (fallbackError) {
                console.error('Error fetching sessions fallback:', fallbackError);
            } else {
                setSessions(fallbackData.map(s => {
                    const participants = (s.session_participants as any[])?.filter(p => p.buddies).map(p => p.buddies.name) || [];
                    return {
                        ...s,
                        participant_count: participants.length,
                        participants: participants,
                        whisky_count: 0
                    };
                }) || []);
            }
        } else {
            setSessions(data.map(s => {
                const participants = (s.session_participants as any[])?.filter(p => p.buddies).map(p => p.buddies.name) || [];
                return {
                    ...s,
                    participant_count: participants.length,
                    participants: participants,
                    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 (
        <div className="bg-zinc-900 rounded-3xl p-6 border border-zinc-800 shadow-xl transition-all duration-300">
            <div className="flex items-center justify-between mb-6">
                <h3 className="text-sm font-bold uppercase tracking-[0.2em] flex items-center gap-2 text-zinc-400">
                    <Calendar size={18} className="text-orange-600" />
                    {t('session.title')}
                    {!isCollapsed && sessions.length > 0 && (
                        <span className="text-[10px] font-bold opacity-50 ml-2">({sessions.length})</span>
                    )}
                </h3>
                <button
                    onClick={handleToggleCollapse}
                    className="p-2 hover:bg-zinc-800 rounded-xl transition-colors text-zinc-500 hover:text-orange-600"
                    title={isCollapsed ? 'Aufklappen' : 'Einklappen'}
                >
                    {isCollapsed ? <ChevronDown size={20} /> : <ChevronUp size={20} />}
                </button>
            </div>

            {!isCollapsed && (
                <>
                    <form onSubmit={handleCreateSession} className="flex gap-2 mb-6">
                        <input
                            type="text"
                            value={newName}
                            onChange={(e) => setNewName(e.target.value)}
                            placeholder={t('session.sessionName')}
                            className="flex-1 bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2 text-sm text-zinc-50 placeholder:text-zinc-600 focus:outline-hidden focus:border-orange-600 transition-colors"
                        />
                        <button
                            type="submit"
                            disabled={isCreating || !newName.trim()}
                            className="bg-orange-600 hover:bg-orange-700 text-white p-2 rounded-xl transition-all disabled:opacity-50"
                        >
                            {isCreating ? <Loader2 size={20} className="animate-spin" /> : <Plus size={20} />}
                        </button>
                    </form>

                    {isLoading ? (
                        <div className="flex justify-center py-12 text-zinc-700">
                            <Loader2 size={32} className="animate-spin" />
                        </div>
                    ) : sessions.length === 0 ? (
                        <div className="text-center py-12 bg-zinc-950/50 rounded-[32px] border border-dashed border-zinc-800">
                            <div className="w-16 h-16 mx-auto rounded-full bg-zinc-900 flex items-center justify-center mb-6 border border-white/5 shadow-inner">
                                <Calendar size={28} className="text-zinc-700" />
                            </div>
                            <p className="text-sm font-black text-zinc-400 mb-2 uppercase tracking-widest">{t('session.noSessions') || 'Keine Sessions'}</p>
                            <p className="text-[10px] text-zinc-600 font-bold uppercase tracking-tight max-w-[200px] mx-auto leading-relaxed">
                                Erstelle eine Tasting-Session um deine Drams zeitlich zu ordnen.
                            </p>
                        </div>
                    ) : (
                        <div className="space-y-4">
                            {sessions.map((session) => (
                                <div
                                    key={session.id}
                                    className={`group relative flex items-center justify-between p-5 rounded-[28px] border transition-all duration-500 overflow-hidden ${activeSession?.id === session.id
                                        ? 'bg-orange-500/3 border-orange-500/40 shadow-[0_0_40px_rgba(234,88,12,0.1)]'
                                        : 'bg-zinc-950/50 border-white/5 hover:border-white/10'
                                        }`}
                                >
                                    {/* Active Glow Decor */}
                                    {activeSession?.id === session.id && (
                                        <div className="absolute top-0 right-0 w-32 h-32 bg-orange-600/10 blur-[60px] -mr-16 -mt-16 pointer-events-none" />
                                    )}

                                    <Link href={`/sessions/${session.id}`} className="flex-1 space-y-2 min-w-0 z-10">
                                        <div className="flex items-center gap-3">
                                            <div className={`font-black text-xl tracking-tight truncate ${activeSession?.id === session.id ? 'text-white' : 'text-zinc-200 group-hover:text-white transition-colors'}`}>
                                                {session.name}
                                            </div>
                                            {session.ended_at && (
                                                <span className="text-[8px] font-black uppercase px-2 py-0.5 rounded-full bg-zinc-800/50 border border-zinc-700/50 text-zinc-500 tracking-widest">Archiv</span>
                                            )}
                                        </div>
                                        <div className={`flex items-center gap-5 text-[10px] font-black uppercase tracking-[0.15em] ${activeSession?.id === session.id ? 'text-orange-500/80' : 'text-zinc-500'}`}>
                                            <span className="flex items-center gap-2">
                                                <Calendar size={13} strokeWidth={2.5} />
                                                {new Date(session.scheduled_at).toLocaleDateString(locale === 'de' ? 'de-DE' : 'en-US')}
                                            </span>
                                            {session.whisky_count! > 0 && (
                                                <span className="flex items-center gap-2">
                                                    <GlassWater size={13} strokeWidth={2.5} />
                                                    {session.whisky_count}
                                                </span>
                                            )}
                                        </div>
                                        {session.participants && session.participants.length > 0 && (
                                            <div className="pt-2">
                                                <AvatarStack names={session.participants} limit={5} />
                                            </div>
                                        )}
                                    </Link>

                                    <div className="flex items-center gap-1 z-10">
                                        {activeSession?.id !== session.id ? (
                                            !session.ended_at ? (
                                                <button
                                                    onClick={(e) => {
                                                        e.preventDefault();
                                                        setActiveSession({ id: session.id, name: session.name });
                                                    }}
                                                    className="p-3 text-zinc-600 hover:text-orange-500 transition-all hover:scale-110 active:scale-95"
                                                    title="Start Session"
                                                >
                                                    <Play size={22} fill="currentColor" className="opacity-40" />
                                                </button>
                                            ) : (
                                                <div className="p-3 text-zinc-800">
                                                    <Check size={20} />
                                                </div>
                                            )
                                        ) : (
                                            <div className="p-3 text-orange-500 animate-pulse">
                                                <Sparkles size={20} />
                                            </div>
                                        )}

                                        <div className="w-px h-8 bg-white/5 mx-1" />

                                        <button
                                            onClick={(e) => handleDeleteSession(e, session.id)}
                                            disabled={!!isDeleting}
                                            className="p-3 text-zinc-700 hover:text-red-500 transition-all opacity-0 group-hover:opacity-100"
                                            title="Session löschen"
                                        >
                                            {isDeleting === session.id ? (
                                                <Loader2 size={18} className="animate-spin" />
                                            ) : (
                                                <Trash2 size={18} />
                                            )}
                                        </button>
                                        <ChevronRight size={20} className="text-zinc-800 group-hover:text-zinc-600 transition-colors" />
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </>
            )}

            {isCollapsed && sessions.length > 0 && (
                <div className="flex items-center gap-2 animate-in fade-in slide-in-from-top-1">
                    <div className="flex -space-x-1.5 overflow-hidden">
                        {sessions.slice(0, 3).map((s, i) => (
                            <div key={s.id} className="w-7 h-7 rounded-lg bg-zinc-950 border border-zinc-800 flex items-center justify-center text-[10px] font-bold text-orange-600 shadow-xs">
                                {s.name[0].toUpperCase()}
                            </div>
                        ))}
                        {sessions.length > 3 && (
                            <div className="w-7 h-7 rounded-lg bg-zinc-950 border border-zinc-800 flex items-center justify-center text-[8px] font-bold text-zinc-500 shadow-xs">
                                +{sessions.length - 3}
                            </div>
                        )}
                    </div>
                    <span className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest ml-1">{sessions.length} Sessions</span>
                </div>
            )}
        </div>
    );
}
