'use client';

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

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;
    });

    useEffect(() => {
        fetchBuddies();
    }, []);

    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-white dark:bg-zinc-900 rounded-3xl p-6 border border-zinc-200 dark:border-zinc-800 shadow-xl transition-all duration-300">
            <div className="flex items-center justify-between mb-6">
                <h3 className="text-xl font-bold flex items-center gap-2 text-zinc-800 dark:text-zinc-100 italic">
                    <Users size={24} className="text-amber-600" />
                    {t('buddy.title')}
                    {!isCollapsed && buddies.length > 0 && (
                        <span className="text-sm font-normal text-zinc-400 not-italic ml-2">({buddies.length})</span>
                    )}
                </h3>
                <button
                    onClick={handleToggleCollapse}
                    className="p-2 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-xl transition-colors text-zinc-400 hover:text-amber-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-50 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-xl px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-amber-500/50"
                        />
                        <button
                            type="submit"
                            disabled={isAdding || !newName.trim()}
                            className="bg-amber-600 hover:bg-amber-700 text-white p-2 rounded-xl transition-all disabled:opacity-50"
                        >
                            {isAdding ? <Loader2 size={20} className="animate-spin" /> : <UserPlus size={20} />}
                        </button>
                    </form>

                    {isLoading ? (
                        <div className="flex justify-center py-8 text-zinc-400">
                            <Loader2 size={24} className="animate-spin" />
                        </div>
                    ) : buddies.length === 0 ? (
                        <div className="text-center py-8 text-zinc-500 text-sm">
                            {t('buddy.noBuddies')}
                        </div>
                    ) : (
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 max-h-[400px] overflow-y-auto pr-2 scrollbar-thin scrollbar-thumb-zinc-200 dark:scrollbar-thumb-zinc-800">
                            {buddies.map((buddy) => (
                                <div
                                    key={buddy.id}
                                    className="flex items-center justify-between p-4 bg-white dark:bg-zinc-800/40 rounded-3xl border border-zinc-100 dark:border-zinc-800 group hover:border-amber-500/30 hover:shadow-md transition-all duration-300"
                                >
                                    <div className="flex items-center gap-3">
                                        <div className="w-10 h-10 rounded-2xl bg-amber-50 dark:bg-amber-900/20 flex items-center justify-center text-amber-600 dark:text-amber-500 font-bold shadow-inner">
                                            {buddy.name[0].toUpperCase()}
                                        </div>
                                        <div className="flex flex-col">
                                            <span className="font-bold text-zinc-800 dark:text-zinc-100 text-sm tracking-tight">{buddy.name}</span>
                                            {buddy.buddy_profile_id && (
                                                <span className="text-[9px] font-black uppercase text-green-600 dark:text-green-500 tracking-widest">{t('common.link')}</span>
                                            )}
                                        </div>
                                    </div>
                                    <button
                                        onClick={() => handleDeleteBuddy(buddy.id)}
                                        className="text-zinc-300 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-all p-2 hover:bg-red-50 dark:hover:bg-red-900/10 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-amber-50 dark:bg-amber-900/20 border border-amber-200/50 dark:border-amber-800/50 flex items-center justify-center text-[10px] font-black text-amber-600 dark:text-amber-500 shadow-sm">
                                {b.name[0].toUpperCase()}
                            </div>
                        ))}
                        {buddies.length > 5 && (
                            <div className="w-7 h-7 rounded-lg bg-zinc-100 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 flex items-center justify-center text-[8px] font-black text-zinc-500 shadow-sm">
                                +{buddies.length - 5}
                            </div>
                        )}
                    </div>
                    <span className="text-[10px] text-zinc-400 font-black uppercase tracking-widest ml-1">{buddies.length} Buddies</span>
                </div>
            )}
        </div>
    );
}
