"use client";

import React, { useEffect, useState } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/navigation";
import { Navigation } from "swiper/modules";
import { Heart, Clock, Star, ChevronLeft, ChevronRight } from "lucide-react";
import { useRouter } from "next/navigation";
import { useSelector } from "react-redux";
import { RootState } from "@/store/store";
import apis from "@/utils/apis";
import { getValidImage } from "@/lib/utils";
import { useGlobalContext } from "@/context/Provider";

interface PopularRestaurantsProps {
    selectedCategoryId?: string | null;
    categoryType?: string;
    title?: string;
}

const PopularRestaurants: React.FC<PopularRestaurantsProps> = ({
    selectedCategoryId,
    categoryType = "food",
    title = "Popular Restaurants",
}) => {
    const router = useRouter();
    const { Toast, userInfo } = useGlobalContext();
    const [restaurants, setRestaurants] = useState<any[]>([]);
    const [loading, setLoading] = useState<boolean>(true);
    const [location, setLocation] = useState<{ lat: number; long: number } | null>(null);

    const selectedAddress = useSelector(
        (state: RootState) => state.user.profile.selectedAddress
    );

    const navPrevClass = `popular-prev-${categoryType.replace(/[^a-zA-Z0-9]/g, "")}`;
    const navNextClass = `popular-next-${categoryType.replace(/[^a-zA-Z0-9]/g, "")}`;

    const fetchPopularStores = async (lat?: number, long?: number) => {
        try {
            setLoading(true);
            const params = new URLSearchParams({
                type: categoryType,
                page: "1",
                limit: "1000",
            });

            if (lat && long) {
                params.append("lat", String(lat));
                params.append("long", String(long));
            }
            if (selectedCategoryId && selectedCategoryId !== "all") {
                params.append("category", selectedCategoryId);
            }

            const response = await apis.restaurant.getNearestPopularStores(params.toString());
            const list = response?.data || response?.data?.data || [];
            setRestaurants(Array.isArray(list) ? list : []);
        } catch (error) {
            console.error("Error fetching popular restaurants:", error);
            setRestaurants([]);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (selectedAddress?.lat && selectedAddress?.long) {
            fetchPopularStores(parseFloat(selectedAddress.lat), parseFloat(selectedAddress.long));
        } else if (location) {
            fetchPopularStores(location.lat, location.long);
        } else {
            navigator.geolocation.getCurrentPosition(
                ({ coords }) => {
                    const lat = coords.latitude;
                    const long = coords.longitude;
                    setLocation({ lat, long });
                    fetchPopularStores(lat, long);
                },
                () => {
                    fetchPopularStores();
                }
            );
        }
    }, [selectedAddress, selectedCategoryId, categoryType]);

    const handleFavourite = async (e: React.MouseEvent, id: string, isFav: boolean) => {
        e.stopPropagation();
        if (!userInfo) {
            Toast.error("Please login to add to favourites");
            return;
        }
        try {
            const payload = {
                restaurant_id: id,
                status: isFav ? "dislike" : "favourite",
            };
            const apiRes = await apis.Favourite.toggle(payload);
            if (apiRes) {
                setRestaurants((prev) =>
                    prev.map((item) =>
                        item._id === id ? { ...item, is_fav: !isFav } : item
                    )
                );
                Toast.success(isFav ? "Removed from favourites" : "Added to favourites");
            }
        } catch (error) {
            console.error("Error toggling favourite:", error);
        }
    };

    if (!loading && restaurants.length === 0) {
        return null;
    }

    if (restaurants.length === 0 && !loading) {
        return null;
    }

    return (
        <div className="max-w-7xl mx-auto my-8 px-4 sm:px-6 lg:px-8">
            <div className="flex items-center justify-between mb-6">
                <h2 className="text-2xl sm:text-3xl font-bold text-gray-900 tracking-tight">
                    {title}
                </h2>
                {restaurants.length > 3 && (
                    <div className="flex items-center gap-2">
                        <button className={`${navPrevClass} w-9 h-9 rounded-full bg-white border border-gray-200 shadow-sm flex items-center justify-center text-gray-700 hover:bg-gray-50 hover:border-gray-300 transition-all disabled:opacity-40 disabled:cursor-not-allowed`}>
                            <ChevronLeft className="w-5 h-5" />
                        </button>
                        <button className={`${navNextClass} w-9 h-9 rounded-full bg-primary text-white shadow-sm flex items-center justify-center hover:bg-primary/90 transition-all disabled:opacity-40 disabled:cursor-not-allowed`}>
                            <ChevronRight className="w-5 h-5" />
                        </button>
                    </div>
                )}
            </div>

            {loading ? (
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                    {[1, 2, 3, 4].map((i) => (
                        <div key={i} className="bg-white rounded-2xl p-3 border border-gray-100 animate-pulse">
                            <div className="w-full h-44 bg-gray-200 rounded-xl mb-3" />
                            <div className="h-5 bg-gray-200 rounded w-3/4 mb-2" />
                            <div className="h-4 bg-gray-200 rounded w-1/2" />
                        </div>
                    ))}
                </div>
            ) : (
                <Swiper
                    modules={[Navigation]}
                    navigation={{
                        prevEl: `.${navPrevClass}`,
                        nextEl: `.${navNextClass}`,
                    }}
                    spaceBetween={20}
                    slidesPerView={1.15}
                    breakpoints={{
                        640: { slidesPerView: 2.2, spaceBetween: 20 },
                        768: { slidesPerView: 3, spaceBetween: 24 },
                        1024: { slidesPerView: 4, spaceBetween: 24 },
                    }}
                    className="py-2"
                >
                    {restaurants.map((restaurant) => {
                        const prepTime = restaurant.average_preparing_time
                            ? `${Math.max(restaurant.average_preparing_time - 5, 5)}-${restaurant.average_preparing_time} mins`
                            : null;

                        const imageSrc = getValidImage(
                            restaurant.image ||
                            (restaurant.uploadRestaurantPhotos && restaurant.uploadRestaurantPhotos[0])
                        );

                        return (
                            <SwiperSlide key={restaurant._id}>
                                <div
                                    onClick={() => {
                                        if (categoryType === "food") {
                                            router.push(`/restaurant?id=${restaurant._id}`);
                                        } else {
                                            router.push(`/grocery/${restaurant._id}?type=${categoryType}`);
                                        }
                                    }}
                                    className="group bg-white rounded-2xl overflow-hidden border border-gray-100 shadow-sm hover:shadow-md transition-all duration-300 cursor-pointer flex flex-col h-full"
                                >
                                    {/* Image Container */}
                                    <div className="relative w-full h-44 sm:h-48 overflow-hidden bg-gray-100">
                                        <img
                                            src={imageSrc}
                                            alt={restaurant.restaurant_name}
                                            className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                                        />
                                        {/* Heart Icon */}
                                        <button
                                            onClick={(e) => handleFavourite(e, restaurant._id, !!restaurant.is_fav)}
                                            className="absolute top-3 right-3 w-8 h-8 rounded-full bg-white/90 hover:bg-white backdrop-blur-sm shadow-sm flex items-center justify-center transition-transform hover:scale-110 active:scale-95"
                                        >
                                            <Heart
                                                className={`w-4 h-4 transition-colors ${restaurant.is_fav
                                                        ? "fill-red-500 text-red-500"
                                                        : "text-gray-600 hover:text-red-500"
                                                    }`}
                                            />
                                        </button>
                                    </div>

                                    {/* Info Section */}
                                    <div className="p-4 flex flex-col justify-between flex-grow">
                                        <div>
                                            <h3 className="font-bold text-gray-900 text-base sm:text-lg truncate group-hover:text-primary transition-colors text-left">
                                                {restaurant.restaurant_name}
                                            </h3>

                                            <div className="flex items-center justify-between mt-2 text-sm text-gray-600">
                                                {prepTime ? (
                                                    <div className="flex items-center gap-1">
                                                        <Clock className="w-4 h-4 text-gray-400" />
                                                        <span>{prepTime}</span>
                                                    </div>
                                                ) : (
                                                    <div />
                                                )}

                                                {/* Rating Pill */}
                                                {Boolean(restaurant.rating) && Number(restaurant.rating) > 0 && (
                                                    <div className="bg-primary text-white font-bold px-2 py-0.5 rounded-full text-xs flex items-center gap-1 shadow-sm">
                                                        <Star className="w-3 h-3 fill-white" />
                                                        <span>{Number(restaurant.rating).toFixed(1)}</span>
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </SwiperSlide>
                        );
                    })}
                </Swiper>
            )}
        </div>
    );
};

export default PopularRestaurants;
