"use client";

import React, { useEffect, useState } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";
import { Pagination } from "swiper/modules";
import apis, { BUCKET_ROOT } from "@/utils/apis";
import { useRouter } from "next/navigation";
import { useSelector } from "react-redux";
import { RootState } from "@/store/store";

interface Restaurant {
    id: string;
    title: string;
    price: string;
    discountedPrice?: string;
    rating: string;
    image: string;
    restaurantId: {
        _id: string;
        restaurantName?: string;
    };
    _id: string;
    address?: string;
    status?: string;
    foodType?: string[];
    isQuickPick?: boolean;
    averagePreparingTime?: any;
}

interface FeaturedRestaurantsProps {
    selectedCategoryId: string | null;
}

const FeaturedRestaurants: React.FC<FeaturedRestaurantsProps> = ({ selectedCategoryId }) => {
    const [restaurants, setRestaurants] = useState<Restaurant[]>([]);
    const [error, setError] = useState<string | null>(null);
    const router = useRouter();

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

    const fetchFeaturedRestaurants = async (lat: string, long: string) => {
        try {
            const params = new URLSearchParams({
                lat,
                long,
                response_type: "most_discounted_restaurant",
                category: selectedCategoryId || "",
            });

            const response = await apis.featureList.getNewlyAddedRestaurants(params.toString());
            const result = response.data || [];

            const mappedData: Restaurant[] = result.map((item: any) => ({
                id: item._id,
                title: item.restaurant_name || "Restaurant",
                price: item.restaurant_discount
                    ? `$${item.restaurant_discount.discount}% off`
                    : "",
                discountedPrice: "",
                rating: item.rating ? `${item.rating}` : "0",
                image: item.image
                    ? `${BUCKET_ROOT}${item.image}`
                    : "/default-restaurant.jpg",
                restaurantId: {
                    _id: item._id,
                    restaurantName: item.restaurant_name,
                },
                _id: item._id,
                address: item.address?.name || "Address not available",
                status: item.status || "offline",
                foodType: item.food_type || [],
                isQuickPick: item.is_quick_pick || false,
                averagePreparingTime: item.average_preparing_time || 0,
            }));

            setRestaurants(mappedData);
        } catch (error) {
            console.error("Error fetching featured restaurants:", error);
            setError("Failed to load featured restaurants.");
        }
    };

    useEffect(() => {
        const loadFeaturedRestaurants = async () => {
            try {
                let latitude = "";
                let longitude = "";

                if (selectedAddress?.lat && selectedAddress?.long) {
                    latitude = selectedAddress.lat;
                    longitude = selectedAddress.long;
                    await fetchFeaturedRestaurants(latitude, longitude);
                } else {
                    navigator.geolocation.getCurrentPosition(
                        async (position) => {
                            latitude = position.coords.latitude.toString();
                            longitude = position.coords.longitude.toString();
                            await fetchFeaturedRestaurants(latitude, longitude);
                        },
                        (error) => {
                            console.error("Location error:", error);
                            fetchFeaturedRestaurants("", "");
                        }
                    );
                }
            } catch (error) {
                console.error("Error loading featured restaurants:", error);
                setError("Failed to fetch restaurants. Please try again later.");
            }
        };

        loadFeaturedRestaurants();
    }, [selectedAddress, selectedCategoryId]); // <- Added selectedCategoryId

    const handleCardClick = (restaurantId: string) => {
        router.push(`/restaurant?id=${restaurantId}`);
    };

    const getSwiperBreakpoints = () => {
        const length = restaurants.length;

        const base = {
            640: { slidesPerView: 1 },
            768: { slidesPerView: 2 },
        };

        if (length === 2) return { ...base, 1024: { slidesPerView: 2 } };
        if (length === 3) return { ...base, 1024: { slidesPerView: 3 } };
        return { ...base, 1024: { slidesPerView: 3 }, 1280: { slidesPerView: 4 } };
    };

    const shouldUseLoop = restaurants.length >= 4;
    const shouldUsePagination = restaurants.length > 1;

    if (restaurants.length === 0) return null;

    return (
        <>
            <div className="mb-0 text-center">
                <h2 className="font-bold mb-2 text-h4 sm:text-h3 md:text-h2 lg:text-h1">
                    <span className="text-primary">Featured On</span> ReadyEats
                </h2>
            </div>
            <div className="max-w-7xl mx-auto py-2 px-4">
                <div className="relative">
                    <Swiper
                        slidesPerView={3}
                        spaceBetween={30}
                        navigation={false}
                        pagination={shouldUsePagination ? { clickable: true, dynamicBullets: true } : false}
                        modules={[Pagination]}
                        loop={shouldUseLoop}
                        breakpoints={getSwiperBreakpoints()}
                        className="mySwiper w-full"
                    >
                        {restaurants.map((restaurant) => (
                            <SwiperSlide key={restaurant.id}>
                                <div
                                    className="flex flex-col bg-white rounded-lg shadow-sm border overflow-hidden cursor-pointer hover:shadow-md transition-all duration-300"
                                    onClick={() => handleCardClick(restaurant.restaurantId._id)}
                                >
                                    <div className="w-full h-40 bg-gray-100 overflow-hidden">
                                        <img
                                            src={restaurant.image}
                                            alt={restaurant.title}
                                            className="w-full h-full object-cover"
                                        />
                                    </div>
                                    <div className="p-3 text-left">
                                        <h3 className="text-base font-semibold text-black-800 truncate">
                                            {restaurant?.title}
                                        </h3>
                                        <p className="text-sm text-black-600 mt-1 flex items-center gap-2">
                                            ⭐ {restaurant?.rating}
                                            <span>
                                                • {restaurant?.averagePreparingTime - 5}–
                                                {restaurant?.averagePreparingTime} mins
                                            </span>
                                        </p>
                                    </div>
                                </div>
                            </SwiperSlide>
                        ))}
                    </Swiper>
                </div>
            </div>
        </>
    );
};

export default FeaturedRestaurants;
