// src/pages/LikesPage.jsx
import { Link } from 'react-router-dom';
import { useLikesContext } from '../context/LikesContext.jsx';
import { useBasketContext } from '../context/BasketContext.jsx';

export default function LikesPage() {
    const { likesItems, removeFromLikes, loading, error } = useLikesContext();
    const { addToBasket } = useBasketContext();

    const handleMoveToBasket = async (shmotka) => {
        try {
            await addToBasket(shmotka);
            await removeFromLikes(shmotka.id);
            alert('Товар перенесен в корзину!');
        } catch (err) {
            alert('Ошибка при переносе товара в корзину');
        }
    };

    const handleRemoveFromLikes = async (shmotkaId) => {
        try {
            await removeFromLikes(shmotkaId);
            alert('Товар удален из избранного!');
        } catch (err) {
            alert('Ошибка при удалении из избранного');
        }
    };

    if (loading) {
        return (
            <main className="container my-4">
                <div className="text-center">
                    <div className="spinner-border" role="status">
                        <span className="visually-hidden">Загрузка...</span>
                    </div>
                </div>
            </main>
        );
    }

    if (error) {
        return (
            <main className="container my-4">
                <div className="alert alert-danger" role="alert">
                    {error}
                </div>
            </main>
        );
    }

    if (likesItems.length === 0) {
        return (
            <main className="container my-4">
                <div className="text-center py-5 empty-likes">
                    <h1 className="mb-4">Здесь будут лежать товары, которые тебе понравились</h1>
                    <p className="lead mb-4">А пока здесь так пусто...</p>
                    <img src="img/sad2.jpeg" alt="Пусто" className="img-fluid rounded" style={{maxHeight: "300px"}} />
                    <div className="mt-4">
                        <Link to="/catalog" className="btn btn-lg" style={{backgroundColor: "#00264d", color: "white"}}>
                            <i className="bi bi-arrow-left me-2"></i>Вернуться в каталог
                        </Link>
                    </div>
                </div>
            </main>
        );
    }

    return (
        <main className="container my-4">
            <h2 className="mb-4 text-center">Избранное</h2>
            <div className="row g-3">
                {likesItems.map(shmotka => (
                    <div key={shmotka.id} className="col-md-4">
                        <div className="card h-100 border-0 shadow">
                            <img 
                                src={shmotka.image} 
                                className="card-img-top" 
                                alt={shmotka.name} 
                                style={{ height: '250px', objectFit: 'cover' }}
                                onError={(e) => {
                                    e.target.src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZGRkIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtc2l6ZT0iMTgiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj5ObyBJbWFnZTwvdGV4dD48L3N2Zz4=';
                                }}
                            />
                            <div className="card-body">
                                <h5 className="card-title">{shmotka.name}</h5>
                                <p className="card-text">{shmotka.description}</p>
                                <div className="row">
                                    <div className="col-6">
                                        <h6 className="mb-1">Category:</h6>
                                        <p className="card-text">{shmotka.category}</p>
                                    </div>
                                    <div className="col-6">
                                        <h6 className="mb-1">Condition:</h6>
                                        <p className="card-text">{shmotka.condition}</p>
                                    </div>
                                </div>
                            </div>
                            <div className="card-footer bg-transparent">
                                <div className="d-flex justify-content-between align-items-end">
                                    <span className="fw-bold text-muted fs-3">
                                        ${shmotka.price}
                                    </span>
                                    <div className="d-flex flex-column gap-1">
                                        <button 
                                            className="btn btn-sm btn-outline-primary"
                                            onClick={() => handleMoveToBasket(shmotka)}
                                        >
                                            <i className="bi bi-cart-plus"></i> В корзину
                                        </button>
                                        <button 
                                            className="btn btn-sm btn-outline-danger"
                                            onClick={() => handleRemoveFromLikes(shmotka.id)}
                                        >
                                            <i className="bi bi-trash"></i> Удалить
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                ))}
            </div>
        </main>
    );
}