'use client';

import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
    X, GlassWater, Plus, Users, Calendar,
    ChevronRight, Loader2, Sparkles, Check,
    ArrowRight, User, Terminal, Package, Info
} from 'lucide-react';
import { createClient } from '@/lib/supabase/client';
import { useI18n } from '@/i18n/I18nContext';
import { useAuth } from '@/context/AuthContext';
import { useSession } from '@/context/SessionContext';
import { getHostSplits, getParticipatingSplits } from '@/services/split-actions';
import AvatarStack from './AvatarStack';
import SplitCard from './SplitCard';

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

interface Split {
    id: string;
    slug: string;
    bottleName: string;
    bottleImage?: string;
    totalVolume: number;
    hostShare: number;
    participantCount: number;
    amountCl?: number; // for participating
    status?: string; // for participating
    isActive: boolean;
    hostName?: string;
}

interface TastingHubProps {
    isOpen: boolean;
    onClose: () => void;
}

export default function TastingHub({ isOpen, onClose }: TastingHubProps) {
    const { t, locale } = useI18n();
    const supabase = createClient();
    const { activeSession, setActiveSession } = useSession();
    const { user, isLoading: isAuthLoading } = useAuth();

    const [activeTab, setActiveTab] = useState<'tastings' | 'splits'>('tastings');
    const [mySessions, setMySessions] = useState<Session[]>([]);
    const [guestSessions, setGuestSessions] = useState<Session[]>([]);

    const [mySplits, setMySplits] = useState<Split[]>([]);
    const [participatingSplits, setParticipatingSplits] = useState<Split[]>([]);

    const [isLoading, setIsLoading] = useState(true);
    const [isCreating, setIsCreating] = useState(false);
    const [newName, setNewName] = useState('');

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

    const fetchAll = async () => {
        setIsLoading(true);
        await Promise.all([fetchSessions(), fetchSplits()]);
        setIsLoading(false);
    };

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

        // 1. Fetch My Sessions (Host)
        const { data: hostData, error: hostError } = await supabase
            .from('tasting_sessions')
            .select(`
                *,
                session_participants (
                    buddies (name)
                ),
                tastings (count)
            `)
            .eq('user_id', user.id)
            .order('scheduled_at', { ascending: false });

        // 2. Fetch Sessions I'm participating in (Guest)
        const { data: participantData, error: partError } = await supabase
            .from('tasting_sessions')
            .select(`
                *,
                profiles (username),
                tastings (count),
                session_participants!inner (
                    buddy_id,
                    buddies!inner (
                        buddy_profile_id
                    )
                )
            `)
            .eq('session_participants.buddies.buddy_profile_id', user.id)
            .order('scheduled_at', { ascending: false });

        if (hostData) {
            setMySessions(hostData.map(s => ({
                ...s,
                is_host: true,
                participant_count: (s.session_participants as any[])?.length || 0,
                participants: (s.session_participants as any[])?.filter(p => p.buddies).map(p => p.buddies.name) || [],
                whisky_count: s.tastings[0]?.count || 0
            })));
        }

        if (participantData) {
            // Filter out host sessions (though RLS might already separate them, better safe)
            setGuestSessions(participantData
                .filter(s => s.user_id !== user.id)
                .map(s => ({
                    ...s,
                    is_host: false,
                    host_name: s.profiles?.username || 'Host',
                    participant_count: 0,
                    whisky_count: s.tastings[0]?.count || 0
                })));
        }
    };

    const fetchSplits = async () => {
        const hostRes = await getHostSplits();
        if (hostRes.success && hostRes.splits) {
            setMySplits(hostRes.splits as Split[]);
        }

        const partRes = await getParticipatingSplits();
        if (partRes.success && partRes.splits) {
            setParticipatingSplits(partRes.splits as Split[]);
        }
    };

    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 {
            fetchSessions();
            setNewName('');
            setActiveSession({ id: data.id, name: data.name });
        }
        setIsCreating(false);
    };

    return (
        <AnimatePresence>
            {isOpen && (
                <>
                    {/* Backdrop */}
                    <motion.div
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        onClick={onClose}
                        className="fixed inset-0 bg-black/80 backdrop-blur-sm z-[60]"
                    />

                    {/* Content */}
                    <motion.div
                        initial={{ y: '100%' }}
                        animate={{ y: 0 }}
                        exit={{ y: '100%' }}
                        transition={{ type: 'spring', damping: 25, stiffness: 200 }}
                        className="fixed bottom-0 left-0 right-0 h-[85vh] bg-[#09090b] border-t border-white/10 rounded-t-[40px] z-[70] flex flex-col shadow-2xl overflow-hidden"
                    >
                        {/* Header */}
                        <div className="p-8 pb-4 flex items-center justify-between shrink-0">
                            <div>
                                <div className="flex items-center gap-3 mb-1">
                                    <div className="w-10 h-10 rounded-2xl bg-orange-600/10 flex items-center justify-center text-orange-500">
                                        <GlassWater size={24} />
                                    </div>
                                    <h2 className="text-3xl font-black text-white uppercase tracking-tight">{t('hub.title')}</h2>
                                </div>
                                <p className="text-zinc-500 text-xs font-bold uppercase tracking-[0.2em] ml-1">{t('hub.subtitle')}</p>
                            </div>
                            <button
                                onClick={onClose}
                                className="w-12 h-12 rounded-2xl bg-zinc-900 border border-white/5 flex items-center justify-center text-zinc-400 hover:text-white transition-all active:scale-95"
                            >
                                <X size={24} />
                            </button>
                        </div>

                        {/* Tabs */}
                        <div className="px-8 shrink-0">
                            <div className="bg-zinc-900/50 p-1.5 rounded-2xl flex gap-1 border border-white/5">
                                <button
                                    onClick={() => setActiveTab('tastings')}
                                    className={`flex-1 py-3 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all ${activeTab === 'tastings' ? 'bg-orange-600 text-white shadow-lg' : 'text-zinc-500 hover:text-zinc-300'}`}
                                >
                                    {t('hub.tabs.tastings')}
                                </button>
                                <button
                                    onClick={() => setActiveTab('splits')}
                                    className={`flex-1 py-3 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all ${activeTab === 'splits' ? 'bg-orange-600 text-white shadow-lg' : 'text-zinc-500 hover:text-zinc-300'}`}
                                >
                                    {t('hub.tabs.splits')}
                                </button>
                            </div>
                        </div>

                        {/* Scrolling Content */}
                        <div className="flex-1 overflow-y-auto px-8 pb-24 pt-8 space-y-12">
                            {activeTab === 'tastings' ? (
                                <>
                                    {/* Create Section */}
                                    <section className="space-y-4">
                                        <h3 className="text-[10px] font-black uppercase tracking-[0.3em] text-zinc-500 flex items-center gap-2">
                                            <Plus size={14} className="text-orange-600" /> {t('hub.sections.startSession')}
                                        </h3>
                                        <form onSubmit={handleCreateSession} className="flex gap-2">
                                            <input
                                                type="text"
                                                value={newName}
                                                onChange={(e) => setNewName(e.target.value)}
                                                placeholder={t('hub.placeholders.sessionName')}
                                                className="flex-1 bg-black/40 border border-white/5 rounded-2xl px-6 py-4 text-sm font-bold text-white placeholder:text-zinc-700 focus:outline-none focus:border-orange-600 transition-all ring-inset focus:ring-1 focus:ring-orange-600/50"
                                            />
                                            <button
                                                type="submit"
                                                disabled={isCreating || !newName.trim()}
                                                className="bg-orange-600 hover:bg-orange-500 text-white px-8 rounded-2xl font-black uppercase tracking-widest text-xs transition-all shadow-lg shadow-orange-950/20 disabled:opacity-50 active:scale-95"
                                            >
                                                {isCreating ? <Loader2 size={20} className="animate-spin" /> : 'Go'}
                                            </button>
                                        </form>
                                    </section>

                                    {/* Active Session Highlight */}
                                    {activeSession && (
                                        <section className="space-y-4 animate-in fade-in slide-in-from-bottom-2 duration-500">
                                            <h3 className="text-[10px] font-black uppercase tracking-[0.3em] text-orange-500 flex items-center gap-2">
                                                <Sparkles size={14} /> {t('hub.sections.activeNow')}
                                            </h3>
                                            <div className="bg-orange-600 rounded-[32px] p-8 shadow-2xl shadow-orange-950/40 border border-white/10 relative overflow-hidden group">
                                                <div className="absolute top-0 right-0 p-6 opacity-10 group-hover:opacity-20 transition-opacity">
                                                    <GlassWater size={120} />
                                                </div>
                                                <div className="relative z-10 flex justify-between items-end">
                                                    <div className="space-y-2">
                                                        <p className="text-orange-200 text-xs font-black uppercase tracking-widest">{t('session.activeSession')}</p>
                                                        <h4 className="text-2xl font-black text-white uppercase leading-none">{activeSession.name}</h4>
                                                    </div>
                                                    <button
                                                        onClick={() => {
                                                            onClose();
                                                            window.location.href = `/sessions/${activeSession.id}`;
                                                        }}
                                                        className="px-6 py-3 bg-white text-orange-600 rounded-2xl font-black uppercase tracking-widest text-[10px] shadow-xl hover:scale-105 transition-transform active:scale-95 flex items-center gap-2"
                                                    >
                                                        {t('grid.close')} <ArrowRight size={14} />
                                                    </button>
                                                </div>
                                            </div>
                                        </section>
                                    )}

                                    {/* My Sessions List */}
                                    <section className="space-y-4">
                                        <h3 className="text-[10px] font-black uppercase tracking-[0.3em] text-zinc-500 flex items-center justify-between">
                                            <span className="flex items-center gap-2"><User size={14} className="text-orange-600" /> {t('hub.sections.yourSessions')}</span>
                                            <span className="text-zinc-700">{mySessions.length}</span>
                                        </h3>

                                        {isLoading ? (
                                            <div className="flex justify-center py-12">
                                                <Loader2 size={32} className="animate-spin text-zinc-800" />
                                            </div>
                                        ) : mySessions.length === 0 ? (
                                            <div className="bg-zinc-900/30 border border-dashed border-white/5 rounded-[32px] p-12 text-center">
                                                <Calendar size={32} className="text-zinc-800 mx-auto mb-3" />
                                                <p className="text-zinc-600 font-bold uppercase tracking-widest text-[10px]">{t('hub.placeholders.noSessions')}</p>
                                            </div>
                                        ) : (
                                            <div className="space-y-3">
                                                {mySessions.map((session) => (
                                                    <SessionCard
                                                        key={session.id}
                                                        session={session}
                                                        isActive={activeSession?.id === session.id}
                                                        locale={locale}
                                                        onSelect={() => {
                                                            setActiveSession({ id: session.id, name: session.name });
                                                            onClose();
                                                        }}
                                                    />
                                                ))}
                                            </div>
                                        )}
                                    </section>

                                    {/* Guest Sessions List */}
                                    {guestSessions.length > 0 && (
                                        <section className="space-y-4">
                                            <h3 className="text-[10px] font-black uppercase tracking-[0.3em] text-zinc-500 flex items-center justify-between">
                                                <span className="flex items-center gap-2"><Users size={14} className="text-orange-600" /> {t('hub.sections.participating')}</span>
                                                <span className="text-zinc-700">{guestSessions.length}</span>
                                            </h3>
                                            <div className="space-y-3">
                                                {guestSessions.map((session) => (
                                                    <SessionCard
                                                        key={session.id}
                                                        session={session}
                                                        isActive={activeSession?.id === session.id}
                                                        locale={locale}
                                                        onSelect={() => {
                                                            setActiveSession({ id: session.id, name: session.name });
                                                            onClose();
                                                        }}
                                                    />
                                                ))}
                                            </div>
                                        </section>
                                    )}
                                </>
                            ) : (
                                <>
                                    {/* Split Section */}
                                    <section className="space-y-4">
                                        <h3 className="text-[10px] font-black uppercase tracking-[0.3em] text-zinc-500 flex items-center gap-2">
                                            <Plus size={14} className="text-orange-600" /> {t('hub.sections.startSplit')}
                                        </h3>
                                        <button
                                            onClick={() => {
                                                onClose();
                                                window.location.href = '/splits/create';
                                            }}
                                            className="w-full bg-zinc-900 border border-white/5 hover:border-orange-500/30 rounded-2xl px-6 py-4 text-xs font-black uppercase tracking-widest text-zinc-400 hover:text-white transition-all flex items-center justify-center gap-3"
                                        >
                                            <Package size={18} className="text-orange-600" /> {t('hub.placeholders.openSplitCreator')}
                                        </button>
                                    </section>

                                    {/* My Splits */}
                                    <section className="space-y-4">
                                        <h3 className="text-[10px] font-black uppercase tracking-[0.3em] text-zinc-500 flex items-center justify-between">
                                            <span className="flex items-center gap-2"><Package size={14} className="text-orange-600" /> {t('hub.sections.yourSplits')}</span>
                                            <span className="text-zinc-700">{mySplits.length}</span>
                                        </h3>

                                        {isLoading ? (
                                            <div className="flex justify-center py-12">
                                                <Loader2 size={32} className="animate-spin text-zinc-800" />
                                            </div>
                                        ) : mySplits.length === 0 ? (
                                            <div className="bg-zinc-900/30 border border-dashed border-white/5 rounded-[32px] p-12 text-center">
                                                <Package size={32} className="text-zinc-800 mx-auto mb-3" />
                                                <p className="text-zinc-600 font-bold uppercase tracking-widest text-[10px]">{t('hub.placeholders.noSplits')}</p>
                                            </div>
                                        ) : (
                                            <div className="space-y-3">
                                                {mySplits.map((split) => (
                                                    <SplitCard
                                                        key={split.id}
                                                        split={split}
                                                        onSelect={() => {
                                                            onClose();
                                                            window.location.href = '/splits/manage';
                                                        }}
                                                    />
                                                ))}
                                            </div>
                                        )}
                                    </section>

                                    {/* Participating Splits */}
                                    {participatingSplits.length > 0 && (
                                        <section className="space-y-4">
                                            <h3 className="text-[10px] font-black uppercase tracking-[0.3em] text-zinc-500 flex items-center justify-between">
                                                <span className="flex items-center gap-2"><Users size={14} className="text-orange-600" /> {t('hub.sections.participating')}</span>
                                                <span className="text-zinc-700">{participatingSplits.length}</span>
                                            </h3>
                                            <div className="space-y-3">
                                                {participatingSplits.map((split) => (
                                                    <SplitCard
                                                        key={split.id}
                                                        split={split}
                                                        isParticipant
                                                        onSelect={() => {
                                                            onClose();
                                                            window.location.href = `/splits/${split.slug}`;
                                                        }}
                                                    />
                                                ))}
                                            </div>
                                        </section>
                                    )}
                                </>
                            )}
                        </div>
                    </motion.div>
                </>
            )}
        </AnimatePresence>
    );
}



function SessionCard({ session, isActive, locale, onSelect }: { session: Session, isActive: boolean, locale: string, onSelect: () => void }) {
    return (
        <div
            className={`p-5 rounded-[28px] border transition-all flex items-center justify-between group cursor-pointer ${isActive ? 'bg-zinc-800/50 border-orange-500/30' : 'bg-zinc-900/30 border-white/5 hover:border-white/10 hover:bg-zinc-900/50'}`}
            onClick={onSelect}
        >
            <div className="flex-1 min-w-0 pr-4">
                <div className="flex items-center gap-2 mb-1">
                    <h4 className={`text-base font-black uppercase truncate tracking-tight transition-colors ${isActive ? 'text-orange-500' : 'text-zinc-200'}`}>
                        {session.name}
                    </h4>
                    {session.ended_at && (
                        <span className="text-[7px] font-black uppercase px-1.5 py-0.5 rounded-full bg-zinc-800 border border-white/5 text-zinc-500">Done</span>
                    )}
                </div>
                <div className="flex items-center gap-4 text-[9px] font-black uppercase tracking-[0.15em] text-zinc-600">
                    <span className="flex items-center gap-1">
                        <Calendar size={10} className="text-zinc-700" />
                        {new Date(session.scheduled_at).toLocaleDateString(locale === 'de' ? 'de-DE' : 'en-US')}
                    </span>
                    {!session.is_host && session.host_name && (
                        <span className="flex items-center gap-1">
                            <Terminal size={10} className="text-zinc-700" />
                            By {session.host_name}
                        </span>
                    )}
                    {session.whisky_count! > 0 && (
                        <span className="flex items-center gap-1">
                            <GlassWater size={10} className="text-orange-600/50" />
                            {session.whisky_count}
                        </span>
                    )}
                </div>
                {session.participants && session.participants.length > 0 && (
                    <div className="mt-3">
                        <AvatarStack names={session.participants} limit={4} />
                    </div>
                )}
            </div>

            <div className={`w-10 h-10 rounded-2xl border transition-all flex items-center justify-center ${isActive ? 'bg-orange-600 border-orange-600 text-white shadow-lg shadow-orange-950/20' : 'bg-black/40 border-white/5 text-zinc-700 group-hover:text-zinc-400 group-hover:border-white/10'}`}>
                {isActive ? <Check size={20} /> : <ChevronRight size={20} />}
            </div>
        </div>
    );
}
