'use client';

import { useRouter } from 'next/navigation';
import { ArrowLeft, Calendar, Plus, GlassWater, Loader2, ChevronRight, Users, Sparkles, Clock, Trash2 } from 'lucide-react';
import { useI18n } from '@/i18n/I18nContext';
import { useEffect, useState } from 'react';
import { createClient } from '@/lib/supabase/client';
import Link from 'next/link';
import { useSession } from '@/context/SessionContext';
import { useAuth } from '@/context/AuthContext';
import { deleteSession } from '@/services/delete-session';
import AvatarStack from '@/components/AvatarStack';

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

export default function SessionsPage() {
    const router = useRouter();
    const { t, locale } = useI18n();
    const supabase = createClient();
    const { activeSession, setActiveSession } = useSession();
    const { user, isLoading: isAuthLoading } = useAuth();

    const [sessions, setSessions] = useState<Session[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [isCreating, setIsCreating] = useState(false);
    const [isDeleting, setIsDeleting] = useState<string | null>(null);
    const [newName, setNewName] = useState('');
    const [showCreateForm, setShowCreateForm] = useState(false);

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

    const fetchSessions = async () => {
        setIsLoading(true);
        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 without tastings join
            const { data: fallbackData } = await supabase
                .from('tasting_sessions')
                .select(`*, session_participants (buddies(name))`)
                .order('scheduled_at', { ascending: false });

            if (fallbackData) {
                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, 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,
                    whisky_count: (s.tastings as any[])?.[0]?.count || 0
                };
            }) || []);
        }
        setIsLoading(false);
    };

    const handleCreateSession = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!newName.trim()) return;

        setIsCreating(true);
        const { data, error } = await supabase
            .from('tasting_sessions')
            .insert({ name: newName.trim(), scheduled_at: new Date().toISOString() })
            .select()
            .single();

        if (!error && data) {
            setSessions(prev => [{ ...data, participant_count: 0, whisky_count: 0 }, ...prev]);
            setNewName('');
            setShowCreateForm(false);
            setActiveSession({ id: data.id, name: data.name });
        }
        setIsCreating(false);
    };

    const handleDeleteSession = async (id: string) => {
        setIsDeleting(id);
        const result = await deleteSession(id);
        if (result.success) {
            setSessions(prev => prev.filter(s => s.id !== id));
            if (activeSession?.id === id) {
                setActiveSession(null);
            }
        }
        setIsDeleting(null);
    };

    const formatDate = (date: string) => {
        return new Date(date).toLocaleDateString(locale === 'de' ? 'de-DE' : 'en-US', {
            day: 'numeric',
            month: 'short',
            year: 'numeric'
        });
    };

    const activeSessions = sessions.filter(s => !s.ended_at);
    const pastSessions = sessions.filter(s => s.ended_at);

    return (
        <main className="min-h-screen bg-zinc-950 pb-24">
            {/* Header */}
            <div className="sticky top-0 z-20 bg-zinc-950/95 backdrop-blur-md border-b border-zinc-900">
                <div className="max-w-2xl mx-auto px-4 py-4 flex items-center gap-4">
                    <button
                        onClick={() => router.back()}
                        className="p-2 rounded-xl bg-zinc-900 border border-zinc-800 text-zinc-400 hover:text-white hover:border-zinc-700 transition-colors"
                    >
                        <ArrowLeft size={20} />
                    </button>
                    <div className="flex-1">
                        <h1 className="text-xl font-bold text-white">
                            {t('session.title')}
                        </h1>
                        <p className="text-xs text-zinc-500">
                            {sessions.length} Sessions
                        </p>
                    </div>
                    <button
                        onClick={() => setShowCreateForm(!showCreateForm)}
                        className="p-2.5 bg-orange-600 hover:bg-orange-700 rounded-xl text-white transition-colors"
                    >
                        <Plus size={20} />
                    </button>
                </div>
            </div>

            <div className="max-w-2xl mx-auto px-4 pt-6">
                {/* Create Form */}
                {showCreateForm && (
                    <form onSubmit={handleCreateSession} className="mb-6 p-4 bg-zinc-900 rounded-2xl border border-zinc-800 animate-in fade-in slide-in-from-top-2">
                        <input
                            type="text"
                            value={newName}
                            onChange={(e) => setNewName(e.target.value)}
                            placeholder={t('session.sessionName')}
                            className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-3 text-white placeholder-zinc-600 focus:outline-none focus:border-orange-600 mb-3"
                            autoFocus
                        />
                        <div className="flex gap-2">
                            <button
                                type="button"
                                onClick={() => setShowCreateForm(false)}
                                className="flex-1 py-2 bg-zinc-800 text-zinc-400 rounded-xl text-sm font-bold"
                            >
                                {t('common.cancel')}
                            </button>
                            <button
                                type="submit"
                                disabled={isCreating || !newName.trim()}
                                className="flex-1 py-2 bg-orange-600 hover:bg-orange-700 text-white rounded-xl text-sm font-bold disabled:opacity-50 flex items-center justify-center gap-2"
                            >
                                {isCreating ? <Loader2 size={16} className="animate-spin" /> : <Sparkles size={16} />}
                                Start Session
                            </button>
                        </div>
                    </form>
                )}

                {/* Active Session Banner */}
                {activeSession && (
                    <Link href={`/sessions/${activeSession.id}`}>
                        <div className="mb-6 p-4 bg-gradient-to-r from-orange-600/20 to-orange-500/10 rounded-2xl border border-orange-600/30 flex items-center gap-4 group hover:border-orange-500/50 transition-colors">
                            <div className="relative">
                                <div className="w-12 h-12 rounded-xl bg-orange-600/20 flex items-center justify-center">
                                    <Sparkles size={24} className="text-orange-500" />
                                </div>
                                <span className="absolute -top-1 -right-1 w-3 h-3 bg-orange-500 rounded-full animate-pulse" />
                            </div>
                            <div className="flex-1">
                                <p className="text-[10px] font-bold uppercase tracking-widest text-orange-500/80">
                                    Live Session
                                </p>
                                <p className="text-lg font-bold text-white">
                                    {activeSession.name}
                                </p>
                            </div>
                            <ChevronRight size={20} className="text-orange-500 group-hover:translate-x-1 transition-transform" />
                        </div>
                    </Link>
                )}

                {/* Sessions List */}
                {isLoading ? (
                    <div className="flex justify-center py-20">
                        <Loader2 size={32} className="animate-spin text-orange-600" />
                    </div>
                ) : sessions.length === 0 ? (
                    <div className="text-center py-20">
                        <div className="w-16 h-16 mx-auto rounded-2xl bg-zinc-900 flex items-center justify-center mb-4">
                            <Calendar size={32} className="text-zinc-600" />
                        </div>
                        <p className="text-lg font-bold text-white mb-2">No Sessions Yet</p>
                        <p className="text-sm text-zinc-500 max-w-xs mx-auto">
                            Start your first tasting session to track what you're drinking.
                        </p>
                    </div>
                ) : (
                    <div className="space-y-3">
                        {sessions.map(session => (
                            <div
                                key={session.id}
                                className={`p-4 bg-zinc-900 rounded-2xl border transition-all group ${activeSession?.id === session.id
                                    ? 'border-orange-600/50'
                                    : 'border-zinc-800 hover:border-zinc-700'
                                    }`}
                            >
                                <div className="flex items-center gap-4">
                                    <div className={`w-12 h-12 rounded-xl flex items-center justify-center ${session.ended_at
                                        ? 'bg-zinc-800 text-zinc-500'
                                        : 'bg-orange-600/20 text-orange-500'
                                        }`}>
                                        <GlassWater size={24} />
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <Link href={`/sessions/${session.id}`}>
                                            <h3 className="font-bold text-white truncate hover:text-orange-500 transition-colors">
                                                {session.name}
                                            </h3>
                                        </Link>
                                        <div className="flex items-center gap-3 text-xs text-zinc-500 mt-0.5">
                                            <span className="flex items-center gap-1">
                                                <Clock size={12} />
                                                {formatDate(session.scheduled_at)}
                                            </span>
                                            {session.whisky_count ? (
                                                <span>{session.whisky_count} Whiskys</span>
                                            ) : null}
                                        </div>
                                    </div>

                                    {session.participants && session.participants.length > 0 && (
                                        <AvatarStack names={session.participants} limit={3} size="sm" />
                                    )}

                                    <div className="flex items-center gap-1">
                                        <button
                                            onClick={() => handleDeleteSession(session.id)}
                                            disabled={isDeleting === session.id}
                                            className="p-2 text-zinc-600 hover:text-red-500 hover:bg-zinc-800 rounded-lg opacity-0 group-hover:opacity-100 transition-all"
                                        >
                                            {isDeleting === session.id ? (
                                                <Loader2 size={16} className="animate-spin" />
                                            ) : (
                                                <Trash2 size={16} />
                                            )}
                                        </button>
                                        <Link href={`/sessions/${session.id}`}>
                                            <button className="p-2 text-zinc-500 hover:text-white hover:bg-zinc-800 rounded-lg transition-colors">
                                                <ChevronRight size={18} />
                                            </button>
                                        </Link>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </main>
    );
}
