"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";
import { getValidImage } from "@/lib/utils";

interface FoodItem {
    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 NearByProps {
    selectedCategoryId: string | null;
}

const NearBy: React.FC<NearByProps> = ({ selectedCategoryId }) => {
    const [recommendations, setRecommendations] = useState<FoodItem[]>([]);
    const [error, setError] = useState<string | null>(null);
    const [loading, setLoading] = useState(true);
    const router = useRouter();

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

    // Main effect that triggers API call when selectedCategoryId changes
    useEffect(() => {
        const loadNewlyAddedRestaurants = async () => {
            setLoading(true);
            setError(null);

            try {
                let latitude: string = "";
                let longitude: string = "";

                // Check if we have selected address coordinates
                if (selectedAddress?.lat && selectedAddress?.long) {
                    latitude = selectedAddress.lat;
                    longitude = selectedAddress.long;
                    await fetchNewlyAddedRestaurants(latitude, longitude);
                } else {
                    // Get user's current location
                    navigator.geolocation.getCurrentPosition(
                        async (position) => {
                            latitude = position.coords.latitude.toString();
                            longitude = position.coords.longitude.toString();
                            await fetchNewlyAddedRestaurants(latitude, longitude);
                        },
                        (error) => {
                            console.error("Location error:", error);
                            // Fallback: fetch without coordinates
                            fetchNewlyAddedRestaurants("", "");
                        }
                    );
                }
            } catch (error) {
                console.error("Error loading newly added restaurants:", error);
                setError("Failed to fetch restaurants. Please try again later.");
            } finally {
                setLoading(false);
            }
        };

        loadNewlyAddedRestaurants();
    }, [selectedAddress, selectedCategoryId]);

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

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

            const mappedData: FoodItem[] = 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: getValidImage(item.image ? item.image : item.uploadRestaurantPhotos[0]),
                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,
            }));

            setRecommendations(mappedData);
        } catch (error) {
            console.error("Error fetching newly added restaurants:", error);
            setError("Failed to load newly added restaurants.");
            throw error; // Re-throw to be caught by outer try-catch
        }
    };

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

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

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

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

    const shouldUsePagination = recommendations.length > 1;

    // Loading state
    if (loading) {
        return (
            <div className="max-w-7xl mx-auto py-2 px-4">
                <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">Near By</span> Vendors/Stores
                    </h2>
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                    {[1, 2, 3, 4].map((i) => (
                        <div key={i} className="flex flex-col bg-white rounded-lg shadow-sm border overflow-hidden">
                            <div className="w-full h-40 bg-gray-200 animate-pulse"></div>
                            <div className="p-3">
                                <div className="h-4 bg-gray-200 rounded animate-pulse mb-2"></div>
                                <div className="h-3 bg-gray-200 rounded animate-pulse w-2/3"></div>
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        );
    }

    if (!loading && recommendations.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">Near By</span> Vendors/Stores
                </h2>
            </div>

            {error && <p className="text-red-500 text-center mb-4">{error}</p>}

            {recommendations.length === 0 ? (
                <div className="text-center py-8">
                    <p className="text-gray-500">No near by restaurants available</p>
                </div>
            ) : recommendations.length === 1 ? (
                <div className="max-w-2xl mx-auto py-2 px-4">
                    <div className="flex justify-center">
                        <div className="max-w-xs w-full">
                            <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(recommendations[0].restaurantId._id)}
                            >
                                <div className="w-full h-40 bg-gray-100 overflow-hidden">
                                    <img
                                        src={recommendations[0].image}
                                        alt={recommendations[0].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">
                                        {recommendations[0]?.title}
                                    </h3>
                                    <p className="text-sm text-black-600 mt-1 flex items-center gap-2">
                                        <span>
                                            {recommendations[0]?.averagePreparingTime - 5}–
                                            {recommendations[0]?.averagePreparingTime} mins
                                        </span>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </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]}
                            breakpoints={getSwiperBreakpoints()}
                            className="mySwiper w-full nearby-swiper"
                        >
                            {recommendations.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">
                                                <span>
                                                    {restaurant?.averagePreparingTime - 5}–
                                                    {restaurant?.averagePreparingTime} mins
                                                </span>
                                            </p>
                                        </div>
                                    </div>
                                </SwiperSlide>
                            ))}
                        </Swiper>
                    </div>
                </div>
            )}
        </>
    );
};

export default NearBy;