'use client';

import React, { useState, useEffect } from 'react';
import { createClientComponentClient } from '@supabase/auth-helpers-nextjs';
import { ChevronLeft, Users, Calendar, GlassWater, Plus, Trash2, Loader2, Sparkles, ChevronRight, Play, Square } from 'lucide-react';
import Link from 'next/link';
import { useSession } from '@/context/SessionContext';
import { useParams, useRouter } from 'next/navigation';
import { useI18n } from '@/i18n/I18nContext';

interface Buddy {
    id: string;
    name: string;
}

interface Participant {
    buddy_id: string;
    buddies: {
        name: string;
    };
}

interface Session {
    id: string;
    name: string;
    scheduled_at: string;
}

interface SessionTasting {
    id: string;
    rating: number;
    bottles: {
        id: string;
        name: string;
        distillery: string;
    };
}

export default function SessionDetailPage() {
    const { t } = useI18n();
    const { id } = useParams();
    const router = useRouter();
    const supabase = createClientComponentClient();
    const [session, setSession] = useState<Session | null>(null);
    const [participants, setParticipants] = useState<Participant[]>([]);
    const [tastings, setTastings] = useState<SessionTasting[]>([]);
    const [allBuddies, setAllBuddies] = useState<Buddy[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const { activeSession, setActiveSession } = useSession();
    const [isAddingParticipant, setIsAddingParticipant] = useState(false);

    useEffect(() => {
        fetchSessionData();
    }, [id]);

    const fetchSessionData = async () => {
        setIsLoading(true);

        // Fetch Session
        const { data: sessionData } = await supabase
            .from('tasting_sessions')
            .select('*')
            .eq('id', id)
            .single();

        if (sessionData) {
            setSession(sessionData);

            // Fetch Participants
            const { data: partData } = await supabase
                .from('session_participants')
                .select('buddy_id, buddies(name)')
                .eq('session_id', id);

            setParticipants((partData as any)?.map((p: any) => ({
                buddy_id: p.buddy_id,
                buddies: p.buddies
            })) || []);

            // Fetch Tastings in this session
            const { data: tastingData } = await supabase
                .from('tastings')
                .select('id, rating, bottles(id, name, distillery)')
                .eq('session_id', id);

            setTastings((tastingData as any)?.map((t: any) => ({
                id: t.id,
                rating: t.rating,
                bottles: t.bottles
            })) || []);

            // Fetch all buddies for the picker
            const { data: buddies } = await supabase
                .from('buddies')
                .select('id, name')
                .order('name');
            setAllBuddies(buddies || []);
        }

        setIsLoading(false);
    };

    const handleAddParticipant = async (buddyId: string) => {
        if (participants.some(p => p.buddy_id === buddyId)) return;

        const { data: { user } } = await supabase.auth.getUser();
        if (!user) return;

        const { error } = await supabase
            .from('session_participants')
            .insert([{
                session_id: id,
                buddy_id: buddyId,
                user_id: user.id
            }]);

        if (!error) {
            fetchSessionData();
        }
    };

    const handleRemoveParticipant = async (buddyId: string) => {
        const { error } = await supabase
            .from('session_participants')
            .delete()
            .eq('session_id', id)
            .eq('buddy_id', buddyId);

        if (!error) {
            fetchSessionData();
        }
    };

    if (isLoading) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-zinc-50 dark:bg-black">
                <Loader2 size={48} className="animate-spin text-amber-600" />
            </div>
        );
    }

    if (!session) {
        return (
            <div className="min-h-screen flex flex-col items-center justify-center gap-4 bg-zinc-50 dark:bg-black p-6">
                <h1 className="text-2xl font-bold">Session nicht gefunden</h1>
                <Link href="/" className="text-amber-600 font-bold">Zurück zum Start</Link>
            </div>
        );
    }

    return (
        <main className="min-h-screen bg-zinc-50 dark:bg-black p-4 md:p-12 lg:p-24">
            <div className="max-w-4xl mx-auto space-y-8">
                {/* Back Button */}
                <Link
                    href="/"
                    className="inline-flex items-center gap-2 text-zinc-400 hover:text-amber-600 transition-colors font-bold uppercase text-[10px] tracking-[0.2em]"
                >
                    <ChevronLeft size={16} />
                    Alle Sessions
                </Link>

                {/* Hero */}
                <header className="bg-white dark:bg-zinc-900 rounded-3xl p-8 border border-zinc-200 dark:border-zinc-800 shadow-xl relative overflow-hidden">
                    <div className="absolute top-0 right-0 p-8 opacity-5">
                        <GlassWater size={120} />
                    </div>
                    <div className="relative z-10 flex flex-col md:flex-row justify-between items-start md:items-end gap-6">
                        <div className="space-y-2">
                            <div className="flex items-center gap-2 text-amber-600 font-black uppercase text-[10px] tracking-widest">
                                <Sparkles size={14} />
                                Tasting Session
                            </div>
                            <h1 className="text-4xl md:text-5xl font-black text-zinc-900 dark:text-white tracking-tighter">
                                {session.name}
                            </h1>
                            <div className="flex items-center gap-4 text-zinc-500 font-bold text-sm">
                                <span className="flex items-center gap-1.5">
                                    <Calendar size={16} className="text-zinc-400" />
                                    {new Date(session.scheduled_at).toLocaleDateString('de-DE')}
                                </span>
                                {tastings.length > 0 && (
                                    <span className="flex items-center gap-1.5 transition-all animate-in fade-in slide-in-from-left-2">
                                        <GlassWater size={16} className="text-zinc-400" />
                                        {tastings.length} {tastings.length === 1 ? 'Whisky' : 'Whiskys'}
                                    </span>
                                )}
                            </div>
                        </div>

                        <div className="flex gap-2">
                            {activeSession?.id !== session.id ? (
                                <button
                                    onClick={() => setActiveSession({ id: session.id, name: session.name })}
                                    className="px-6 py-3 bg-amber-600 hover:bg-amber-700 text-white rounded-2xl text-sm font-black uppercase tracking-widest flex items-center gap-2 transition-all shadow-xl shadow-amber-600/20"
                                >
                                    <Play size={18} fill="currentColor" />
                                    Session Starten
                                </button>
                            ) : (
                                <button
                                    onClick={() => setActiveSession(null)}
                                    className="px-6 py-3 bg-zinc-900 dark:bg-zinc-100 text-white dark:text-zinc-900 rounded-2xl text-sm font-black uppercase tracking-widest flex items-center gap-2 border border-zinc-200 dark:border-zinc-800 hover:bg-red-600 hover:text-white dark:hover:bg-red-600 dark:hover:text-white transition-all group"
                                >
                                    <Square size={18} className="text-red-500 group-hover:text-white transition-colors" fill="currentColor" />
                                    Session Stoppen
                                </button>
                            )}
                        </div>
                    </div>
                </header>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
                    {/* Sidebar: Participants */}
                    <aside className="md:col-span-1 space-y-6">
                        <div className="bg-white dark:bg-zinc-900 rounded-3xl p-6 border border-zinc-200 dark:border-zinc-800 shadow-lg">
                            <h3 className="text-sm font-black uppercase tracking-widest text-zinc-400 mb-6 flex items-center gap-2">
                                <Users size={16} className="text-amber-600" />
                                Teilnehmer
                            </h3>

                            <div className="space-y-3 mb-6">
                                {participants.length === 0 ? (
                                    <p className="text-xs text-zinc-500 italic">Noch keine Teilnehmer...</p>
                                ) : (
                                    participants.map((p) => (
                                        <div key={p.buddy_id} className="flex items-center justify-between group">
                                            <span className="text-sm font-bold text-zinc-700 dark:text-zinc-300">{p.buddies.name}</span>
                                            <button
                                                onClick={() => handleRemoveParticipant(p.buddy_id)}
                                                className="text-zinc-300 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-all"
                                            >
                                                <Trash2 size={14} />
                                            </button>
                                        </div>
                                    ))
                                )}
                            </div>

                            <div className="border-t border-zinc-100 dark:border-zinc-800 pt-6">
                                <label className="text-[10px] font-black uppercase tracking-widest text-zinc-400 block mb-3">Buddy hinzufügen</label>
                                <select
                                    onChange={(e) => {
                                        if (e.target.value) handleAddParticipant(e.target.value);
                                        e.target.value = "";
                                    }}
                                    className="w-full bg-zinc-50 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-xl px-3 py-2 text-xs font-bold outline-none focus:ring-2 focus:ring-amber-500/50"
                                >
                                    <option value="">Auswählen...</option>
                                    {allBuddies
                                        .filter(b => !participants.some(p => p.buddy_id === b.id))
                                        .map(b => (
                                            <option key={b.id} value={b.id}>{b.name}</option>
                                        ))
                                    }
                                </select>
                            </div>
                        </div>
                    </aside>

                    {/* Main Content: Bottle List */}
                    <section className="md:col-span-2 space-y-6">
                        <div className="bg-white dark:bg-zinc-900 rounded-3xl p-6 border border-zinc-200 dark:border-zinc-800 shadow-lg">
                            <div className="flex justify-between items-center mb-8">
                                <h3 className="text-sm font-black uppercase tracking-widest text-zinc-400 flex items-center gap-2">
                                    <GlassWater size={16} className="text-amber-600" />
                                    Verkostete Flaschen
                                </h3>
                                <Link
                                    href={`/?session_id=${id}`} // Redirect to home with context
                                    className="bg-amber-600 hover:bg-amber-700 text-white px-4 py-2 rounded-xl text-xs font-black uppercase tracking-widest flex items-center gap-2 transition-all shadow-lg shadow-amber-600/20"
                                >
                                    <Plus size={16} />
                                    Flasche hinzufügen
                                </Link>
                            </div>

                            {tastings.length === 0 ? (
                                <div className="text-center py-12 text-zinc-500 italic text-sm">
                                    Noch keine Flaschen in dieser Session verkostet. 🥃
                                </div>
                            ) : (
                                <div className="space-y-4">
                                    {tastings.map((t) => (
                                        <div key={t.id} className="flex items-center justify-between p-4 bg-zinc-50 dark:bg-zinc-800/50 rounded-2xl border border-zinc-100 dark:border-zinc-800">
                                            <div>
                                                <div className="text-[9px] font-black text-amber-600 uppercase tracking-widest">{t.bottles.distillery}</div>
                                                <div className="font-bold text-zinc-800 dark:text-zinc-100">{t.bottles.name}</div>
                                            </div>
                                            <div className="flex items-center gap-4">
                                                <div className="bg-amber-100 dark:bg-amber-900/30 text-amber-700 px-3 py-1 rounded-xl text-xs font-black">
                                                    {t.rating}/100
                                                </div>
                                                <Link
                                                    href={`/bottles/${t.bottles.id}`}
                                                    className="p-2 text-zinc-300 hover:text-amber-600 transition-colors"
                                                >
                                                    <ChevronRight size={20} />
                                                </Link>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>
                    </section>
                </div>
            </div >
        </main >
    );
}

