'use client';

import { useRouter } from 'next/navigation';
import { ArrowLeft, Users, UserPlus, Loader2, Trash2, Link2, Search } from 'lucide-react';
import { useI18n } from '@/i18n/I18nContext';
import { useEffect, useState } from 'react';
import { createClient } from '@/lib/supabase/client';
import { useAuth } from '@/context/AuthContext';
import { addBuddy, deleteBuddy } from '@/services/buddy';
import BuddyHandshake from '@/components/BuddyHandshake';

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

export default function BuddiesPage() {
    const router = useRouter();
    const { t } = useI18n();
    const supabase = createClient();
    const { user, isLoading: isAuthLoading } = useAuth();

    const [buddies, setBuddies] = useState<Buddy[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [isAdding, setIsAdding] = useState(false);
    const [newName, setNewName] = useState('');
    const [searchQuery, setSearchQuery] = useState('');
    const [isHandshakeOpen, setIsHandshakeOpen] = useState(false);

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

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

        if (!error) {
            setBuddies(data || []);
        }
        setIsLoading(false);
    };

    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('');
        }
        setIsAdding(false);
    };

    const handleDeleteBuddy = async (id: string) => {
        const result = await deleteBuddy(id);
        if (result.success) {
            setBuddies(prev => prev.filter(b => b.id !== id));
        }
    };

    const filteredBuddies = buddies.filter(b =>
        b.name.toLowerCase().includes(searchQuery.toLowerCase())
    );

    const linkedBuddies = filteredBuddies.filter(b => b.buddy_profile_id);
    const unlinkedBuddies = filteredBuddies.filter(b => !b.buddy_profile_id);

    return (
        <main className="min-h-screen bg-zinc-950 pb-24">
            {/* Header */}
            <div className="sticky top-0 z-20 bg-zinc-950/95 backdrop-blur-md border-b border-zinc-900">
                <div className="max-w-2xl mx-auto px-4 py-4 flex items-center gap-4">
                    <button
                        onClick={() => router.back()}
                        className="p-2 rounded-xl bg-zinc-900 border border-zinc-800 text-zinc-400 hover:text-white hover:border-zinc-700 transition-colors"
                    >
                        <ArrowLeft size={20} />
                    </button>
                    <div className="flex-1">
                        <h1 className="text-xl font-bold text-white">
                            {t('buddy.title')}
                        </h1>
                        <p className="text-xs text-zinc-500">
                            {buddies.length} Buddies
                        </p>
                    </div>
                    <button
                        onClick={() => setIsHandshakeOpen(true)}
                        className="p-2.5 bg-zinc-900 hover:bg-zinc-800 border border-zinc-800 hover:border-orange-600/50 rounded-xl text-orange-500 transition-colors"
                    >
                        <Link2 size={20} />
                    </button>
                </div>
            </div>

            <div className="max-w-2xl mx-auto px-4 pt-6">
                {/* Add Buddy Form */}
                <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-900 border border-zinc-800 rounded-xl px-4 py-3 text-white placeholder-zinc-600 focus:outline-none focus:border-orange-600 transition-colors"
                    />
                    <button
                        type="submit"
                        disabled={isAdding || !newName.trim()}
                        className="px-4 bg-orange-600 hover:bg-orange-700 text-white rounded-xl transition-all disabled:opacity-50 flex items-center gap-2"
                    >
                        {isAdding ? (
                            <Loader2 size={20} className="animate-spin" />
                        ) : (
                            <>
                                <UserPlus size={20} />
                                <span className="hidden sm:inline text-sm font-bold">Add</span>
                            </>
                        )}
                    </button>
                </form>

                {/* Search */}
                {buddies.length > 5 && (
                    <div className="relative mb-6">
                        <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500" />
                        <input
                            type="text"
                            placeholder="Search buddies..."
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            className="w-full pl-9 pr-4 py-2.5 bg-zinc-900 border border-zinc-800 rounded-xl text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-orange-600/50"
                        />
                    </div>
                )}

                {/* Buddies List */}
                {isLoading ? (
                    <div className="flex justify-center py-20">
                        <Loader2 size={32} className="animate-spin text-orange-600" />
                    </div>
                ) : buddies.length === 0 ? (
                    <div className="text-center py-20">
                        <div className="w-16 h-16 mx-auto rounded-2xl bg-zinc-900 flex items-center justify-center mb-4">
                            <Users size={32} className="text-zinc-600" />
                        </div>
                        <p className="text-lg font-bold text-white mb-2">{t('buddy.noBuddies')}</p>
                        <p className="text-sm text-zinc-500 max-w-xs mx-auto">
                            Add your tasting friends to share sessions and compare notes.
                        </p>
                    </div>
                ) : (
                    <div className="space-y-6">
                        {/* Linked Buddies */}
                        {linkedBuddies.length > 0 && (
                            <div>
                                <h3 className="text-[10px] font-bold uppercase tracking-widest text-orange-500/80 mb-3 flex items-center gap-2">
                                    <Link2 size={12} />
                                    Linked Accounts
                                </h3>
                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                    {linkedBuddies.map(buddy => (
                                        <BuddyCard
                                            key={buddy.id}
                                            buddy={buddy}
                                            onDelete={handleDeleteBuddy}
                                        />
                                    ))}
                                </div>
                            </div>
                        )}

                        {/* Unlinked Buddies */}
                        {unlinkedBuddies.length > 0 && (
                            <div>
                                {linkedBuddies.length > 0 && (
                                    <h3 className="text-[10px] font-bold uppercase tracking-widest text-zinc-500 mb-3">
                                        Other Buddies
                                    </h3>
                                )}
                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                    {unlinkedBuddies.map(buddy => (
                                        <BuddyCard
                                            key={buddy.id}
                                            buddy={buddy}
                                            onDelete={handleDeleteBuddy}
                                        />
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                )}
            </div>

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

function BuddyCard({ buddy, onDelete }: { buddy: Buddy; onDelete: (id: string) => void }) {
    const { t } = useI18n();
    const [isDeleting, setIsDeleting] = useState(false);

    const handleDelete = async () => {
        setIsDeleting(true);
        await onDelete(buddy.id);
        setIsDeleting(false);
    };

    return (
        <div className="flex items-center justify-between p-4 bg-zinc-900 rounded-2xl border border-zinc-800 group hover:border-zinc-700 transition-all">
            <div className="flex items-center gap-3">
                <div className={`w-11 h-11 rounded-xl flex items-center justify-center font-bold text-lg ${buddy.buddy_profile_id
                        ? 'bg-orange-600/20 text-orange-500 border border-orange-600/30'
                        : 'bg-zinc-800 text-zinc-400 border border-zinc-700'
                    }`}>
                    {buddy.name[0].toUpperCase()}
                </div>
                <div>
                    <p className="font-bold text-white">{buddy.name}</p>
                    {buddy.buddy_profile_id && (
                        <p className="text-[9px] font-bold uppercase tracking-widest text-orange-500/80">
                            {t('common.link')}
                        </p>
                    )}
                </div>
            </div>
            <button
                onClick={handleDelete}
                disabled={isDeleting}
                className="p-2 text-zinc-600 hover:text-red-500 hover:bg-zinc-800 rounded-xl opacity-0 group-hover:opacity-100 transition-all"
            >
                {isDeleting ? (
                    <Loader2 size={16} className="animate-spin" />
                ) : (
                    <Trash2 size={16} />
                )}
            </button>
        </div>
    );
}
