"use client";

import React, { useState, useEffect } from 'react';
import { Heart, Loader2, Search, MapPin, Star, ExternalLink } from 'lucide-react';
import Link from 'next/link';
import { useUser } from '../UserProvider';
import { toast } from 'react-hot-toast';

interface Favorite {
    id: string;
    business: {
        id: string;
        name: string;
        category: string;
        location: string;
        description: string;
        logoUrl: string;
        slug: string | null;
        rating: number;
        viewCount: number;
    }
}

const DashboardFavorites = () => {
    const { user } = useUser();
    const [favorites, setFavorites] = useState<Favorite[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');

    useEffect(() => {
        if (user) {
            fetchFavorites();
        }
    }, [user]);

    const fetchFavorites = async () => {
        try {
            const res = await fetch('/api/favorites', {
                headers: { 'x-user-id': user?.id || '' }
            });
            const data = await res.json();
            if (!data.error) {
                setFavorites(data);
            }
        } catch (error) {
            console.error('Error fetching favorites:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleRemoveFavorite = async (e: React.MouseEvent, businessId: string) => {
        e.preventDefault();
        e.stopPropagation();

        try {
            const res = await fetch('/api/favorites', {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    'x-user-id': user?.id || ''
                },
                body: JSON.stringify({ businessId })
            });
            const data = await res.json();
            if (!data.error) {
                setFavorites(favorites.filter(f => f.business.id !== businessId));
                toast.success('Retiré des favoris');
            }
        } catch (error) {
            toast.error('Erreur lors de la suppression');
        }
    };

    const filteredFavorites = favorites.filter(f => 
        f.business.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        f.business.category.toLowerCase().includes(searchTerm.toLowerCase())
    );

    if (loading) {
        return (
            <div className="flex items-center justify-center py-20">
                <Loader2 className="w-8 h-8 animate-spin text-brand-600" />
            </div>
        );
    }

    return (
        <div className="space-y-6">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <h2 className="text-2xl font-bold font-serif text-gray-900">Mes Favoris</h2>
                <div className="relative">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                    <input
                        type="text"
                        placeholder="Rechercher..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="pl-10 pr-4 py-2 bg-white border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-brand-500 outline-none w-full sm:w-64"
                    />
                </div>
            </div>

            {filteredFavorites.length === 0 ? (
                <div className="bg-white rounded-xl border border-dashed border-gray-300 p-12 text-center">
                    <div className="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4">
                        <Heart className="w-8 h-8 text-gray-200" />
                    </div>
                    <h3 className="text-lg font-bold text-gray-900 mb-1">Aucun favori</h3>
                    <p className="text-gray-500 max-w-sm mx-auto mb-6">
                        Vous n'avez pas encore ajouté d'entrepreneur à vos favoris. Parcourez l'annuaire pour découvrir des pépites !
                    </p>
                    <Link 
                        href="/annuaire" 
                        className="inline-flex items-center px-4 py-2 bg-brand-600 text-white font-bold rounded-lg hover:bg-brand-700 transition-colors"
                    >
                        Explorer l'annuaire
                    </Link>
                </div>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {filteredFavorites.map((fav) => (
                        <div key={fav.id} className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden group flex flex-col h-full relative">
                            <div className="relative h-32 bg-gray-100">
                                <img 
                                    src={fav.business.logoUrl || `https://picsum.photos/seed/${fav.business.id}/400/200`} 
                                    alt={fav.business.name}
                                    className="w-full h-full object-cover"
                                />
                                <div className="absolute inset-0 bg-black/20 group-hover:bg-black/40 transition-colors" />
                                <button 
                                    onClick={(e) => handleRemoveFavorite(e, fav.business.id)}
                                    className="absolute top-2 right-2 p-2 bg-white rounded-full text-red-500 shadow-sm hover:scale-110 transition-transform"
                                    title="Retirer des favoris"
                                >
                                    <Heart className="w-4 h-4 fill-current" />
                                </button>
                            </div>
                            
                            <div className="p-4 flex-1 flex flex-col">
                                <h4 className="font-bold text-gray-900 truncate mb-1">{fav.business.name}</h4>
                                <p className="text-[10px] text-brand-600 font-bold uppercase tracking-wider mb-2">{fav.business.category}</p>
                                
                                <div className="flex items-center text-xs text-gray-500 mb-2">
                                    <MapPin className="w-3.5 h-3.5 mr-1" />
                                    {fav.business.location}
                                </div>
                                
                                <div className="flex items-center gap-3 mt-auto pt-3 border-t border-gray-50">
                                    <div className="flex items-center">
                                        <Star className="w-3 h-3 text-yellow-400 fill-current" />
                                        <span className="text-[11px] font-bold ml-1">{fav.business.rating}</span>
                                    </div>
                                    <Link 
                                        href={`/annuaire/${fav.business.slug || fav.business.id}`}
                                        className="ml-auto text-[11px] font-bold text-brand-600 flex items-center gap-1 hover:underline"
                                    >
                                        Voir la fiche
                                        <ExternalLink className="w-3 h-3" />
                                    </Link>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
};

export default DashboardFavorites;
