'use client';

import React, { useState, useEffect } from 'react';
import { createClient } from '@/lib/supabase/client';
import { Users, UserPlus, Trash2, Loader2, ChevronDown, ChevronUp, Link2 } from 'lucide-react';
import { useI18n } from '@/i18n/I18nContext';
import { useAuth } from '@/context/AuthContext';
import { addBuddy, deleteBuddy } from '@/services/buddy';
import BuddyHandshake from './BuddyHandshake';

interface Buddy {
    id: string;
    name: string;
    buddy_profile_id: string | null;
}

export default function BuddyList() {
    const { t } = useI18n();
    const supabase = createClient();
    const [buddies, setBuddies] = useState<Buddy[]>([]);
    const [newName, setNewName] = useState('');
    const [isLoading, setIsLoading] = useState(true);
    const [isAdding, setIsAdding] = useState(false);
    const [isCollapsed, setIsCollapsed] = useState(() => {
        if (typeof window !== 'undefined') {
            return localStorage.getItem('whisky-buddies-collapsed') === 'true';
        }
        return false;
    });
    const [isHandshakeOpen, setIsHandshakeOpen] = useState(false);
    const { user, isLoading: isAuthLoading } = useAuth();

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

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

        const { data, error } = await supabase
            .from('buddies')
            .select('*')
            .order('name');

        if (error) {
            console.error('Error fetching buddies:', error);
        } else {
            setBuddies(data || []);
        }
        setIsLoading(false);
    };

    const handleToggleCollapse = () => {
        const nextState = !isCollapsed;
        setIsCollapsed(nextState);
        localStorage.setItem('whisky-buddies-collapsed', String(nextState));
    };

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

        setIsAdding(true);
        const result = await addBuddy({ name: newName.trim() });

        if (result.success && result.data) {
            setBuddies(prev => [...[result.data], ...prev].sort((a, b) => a.name.localeCompare(b.name)));
            setNewName('');
        } else {
            console.error('Error adding buddy:', result.error);
        }
        setIsAdding(false);
    };

    const handleDeleteBuddy = async (id: string) => {
        const result = await deleteBuddy(id);

        if (result.success) {
            setBuddies(prev => prev.filter(b => b.id !== id));
        } else {
            console.error('Error deleting buddy:', result.error);
        }
    };

    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">
                    <Users size={18} className="text-orange-600" />
                    {t('buddy.title')}
                    {!isCollapsed && buddies.length > 0 && (
                        <span className="text-[10px] font-bold opacity-50 ml-2">({buddies.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={handleAddBuddy} className="flex gap-2 mb-6">
                        <input
                            type="text"
                            value={newName}
                            onChange={(e) => setNewName(e.target.value)}
                            placeholder={t('buddy.placeholder')}
                            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-none focus:border-orange-600 transition-colors"
                        />
                        <button
                            type="submit"
                            disabled={isAdding || !newName.trim()}
                            className="bg-orange-600 hover:bg-orange-700 text-white p-2 rounded-xl transition-all disabled:opacity-50"
                        >
                            {isAdding ? <Loader2 size={20} className="animate-spin" /> : <UserPlus size={20} />}
                        </button>
                    </form>

                    {/* Link Account Button */}
                    <button
                        onClick={() => setIsHandshakeOpen(true)}
                        className="w-full mb-6 py-3 bg-zinc-950 hover:bg-zinc-800 border border-zinc-800 hover:border-orange-600/50 rounded-2xl transition-all flex items-center justify-center gap-2 group"
                    >
                        <Link2 size={16} className="text-orange-600" />
                        <span className="text-xs font-bold uppercase tracking-widest text-zinc-400 group-hover:text-orange-500 transition-colors">
                            Account verbinden
                        </span>
                    </button>

                    {isLoading ? (
                        <div className="flex justify-center py-8 text-zinc-500">
                            <Loader2 size={24} className="animate-spin" />
                        </div>
                    ) : buddies.length === 0 ? (
                        <div className="text-center py-8">
                            <div className="w-14 h-14 mx-auto rounded-2xl bg-zinc-800/50 flex items-center justify-center mb-4">
                                <Users size={24} className="text-zinc-500" />
                            </div>
                            <p className="text-sm font-bold text-zinc-400 mb-1">Keine Buddies</p>
                            <p className="text-xs text-zinc-600 max-w-[200px] mx-auto">
                                Füge Freunde hinzu um deren Empfehlungen zu sehen
                            </p>
                        </div>
                    ) : (
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 max-h-[400px] overflow-y-auto pr-2 scrollbar-none">
                            {buddies.map((buddy) => (
                                <div
                                    key={buddy.id}
                                    className="flex items-center justify-between p-4 bg-zinc-950 rounded-2xl border border-zinc-800 group hover:border-zinc-700 transition-all duration-300"
                                >
                                    <div className="flex items-center gap-3">
                                        <div className="w-10 h-10 rounded-xl bg-zinc-900 border border-zinc-800 flex items-center justify-center text-orange-600 font-bold shadow-inner">
                                            {buddy.name[0].toUpperCase()}
                                        </div>
                                        <div className="flex flex-col">
                                            <span className="font-bold text-zinc-50 text-sm tracking-tight">{buddy.name}</span>
                                            {buddy.buddy_profile_id && (
                                                <span className="text-[9px] font-bold uppercase text-orange-500/80 tracking-widest">{t('common.link')}</span>
                                            )}
                                        </div>
                                    </div>
                                    <button
                                        onClick={() => handleDeleteBuddy(buddy.id)}
                                        className="text-zinc-600 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-all p-2 hover:bg-zinc-800 rounded-xl"
                                    >
                                        <Trash2 size={16} />
                                    </button>
                                </div>
                            ))}
                        </div>
                    )}
                </>
            )}

            {isCollapsed && buddies.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">
                        {buddies.slice(0, 5).map((b, i) => (
                            <div key={b.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-sm">
                                {b.name[0].toUpperCase()}
                            </div>
                        ))}
                        {buddies.length > 5 && (
                            <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-sm">
                                +{buddies.length - 5}
                            </div>
                        )}
                    </div>
                    <span className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest ml-1">{buddies.length} Buddies</span>
                </div>
            )}

            {/* Buddy Handshake Dialog */}
            <BuddyHandshake
                isOpen={isHandshakeOpen}
                onClose={() => setIsHandshakeOpen(false)}
                onSuccess={() => {
                    setIsHandshakeOpen(false);
                    fetchBuddies();
                }}
            />
        </div>
    );
}
