'use client';

import React, { useState, useEffect } from 'react';
import { createClientComponentClient } from '@supabase/auth-helpers-nextjs';
import { Users, UserPlus, Trash2, User, Loader2 } from 'lucide-react';
import { useI18n } from '@/i18n/I18nContext';

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

export default function BuddyList() {
    const { t } = useI18n();
    const supabase = createClientComponentClient();
    const [buddies, setBuddies] = useState<Buddy[]>([]);
    const [newName, setNewName] = useState('');
    const [isLoading, setIsLoading] = useState(true);
    const [isAdding, setIsAdding] = useState(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 handleAddBuddy = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!newName.trim()) return;

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

        const { data, error } = await supabase
            .from('buddies')
            .insert([{ name: newName.trim(), user_id: user.id }])
            .select();

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

    const handleDeleteBuddy = async (id: string) => {
        const { error } = await supabase
            .from('buddies')
            .delete()
            .eq('id', id);

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

    return (
        <div className="bg-white dark:bg-zinc-900 rounded-3xl p-6 border border-zinc-200 dark:border-zinc-800 shadow-xl">
            <h3 className="text-xl font-bold mb-6 flex items-center gap-2 text-zinc-800 dark:text-zinc-100 italic">
                <Users size={24} className="text-amber-600" />
                {t('buddy.title')}
            </h3>

            <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="space-y-2 max-h-[300px] overflow-y-auto scrollbar-hide">
                    {buddies.map((buddy) => (
                        <div
                            key={buddy.id}
                            className="flex items-center justify-between p-3 bg-zinc-50 dark:bg-zinc-800/50 rounded-2xl border border-zinc-100 dark:border-zinc-800 group hover:border-amber-500/30 transition-all"
                        >
                            <div className="flex items-center gap-3">
                                <div className="w-8 h-8 rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center text-amber-700 dark:text-amber-500">
                                    <User size={16} />
                                </div>
                                <div>
                                    <span className="font-semibold text-zinc-800 dark:text-zinc-200 text-sm">{buddy.name}</span>
                                    {buddy.buddy_profile_id && (
                                        <span className="ml-2 inline-block px-1.5 py-0.5 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-500 text-[8px] font-black uppercase rounded">{t('common.link')}</span>
                                    )}
                                </div>
                            </div>
                            <button
                                onClick={() => handleDeleteBuddy(buddy.id)}
                                className="text-zinc-400 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-all p-1"
                            >
                                <Trash2 size={16} />
                            </button>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}
