"use client";
import Image from "next/image";
import DummyImg from "@/assets/images/burger.jpg";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/pagination";
import { Navigation, Pagination } from "swiper/modules";
import { useEffect, useState } from "react";
import apis, { BUCKET_ROOT } from "@/utils/apis";
import { useRouter } from "next/navigation";
import "swiper/css/navigation";
import { useSelector } from "react-redux";
import { RootState } from "@/store/store";

interface QuickPicksProps {
  selectedCategoryId: string | null;
}

const CategoryCard = ({ image, title, count }: any) => (
  <div className="relative w-full max-w-sm rounded-xl overflow-hidden cursor-pointer group">
    <div className="relative h-64 w-full">
      <Image
        src={image}
        alt={title}
        fill
        className="object-cover"
      />

      <div className="absolute inset-0 bg-gradient-to-t from-black/80 to-transparent"></div>
    </div>

    {count && (
      <div className="absolute top-0 right-3 bg-primary text-black font-medium px-2 py-1 rounded-b text-sm">
        -{count}
      </div>
    )}

    <div className="absolute bottom-0 left-0 p-4 w-full">
      <div className="text-xs text-primary font-medium mb-1 text-start">Vendor/Store</div>
      <h3 className="text-white font-bold text-lg text-start">{title}</h3>
    </div>
  </div>
);

const QuickPicks: React.FC<QuickPicksProps> = ({ selectedCategoryId }) => {
  const selectedAddress = useSelector(
    (state: RootState) => state.user.profile.selectedAddress
  );

  const [restaurantList, setRestaurantList] = useState([]);
  const router = useRouter();

  const getList = async () => {
    try {
      let latitude = null;
      let longitude = null;

      if (selectedAddress && selectedAddress.lat && selectedAddress.long) {
        latitude = parseFloat(selectedAddress.lat);
        longitude = parseFloat(selectedAddress.long);
      } else {
        navigator.geolocation.getCurrentPosition(
          async (position) => {
            latitude = position.coords.latitude;
            longitude = position.coords.longitude;

            const params = new URLSearchParams({
              lat: latitude.toString(),
              long: longitude.toString(),
              page: '1',
              limit: '100',
            });

            const apiRes = await apis.restaurant.getQuick(`${params.toString()}`);
            setRestaurantList(apiRes?.data);
          },
          (error) => {
            console.error("Location error:", error);
          }
        );
      }

      if (latitude && longitude) {
        const params = new URLSearchParams({
          lat: latitude.toString(),
          long: longitude.toString(),
          page: '1',
          limit: '100',
          category: selectedCategoryId || ''
        });
        const apiRes = await apis.restaurant.getQuick(`${params.toString()}`);
        setRestaurantList(apiRes?.data);
      }

    } catch (error) {
      console.error("API error:", error);
    }
  };

  useEffect(() => {
    getList();
  }, [selectedAddress, selectedCategoryId]);

  const handleSelect = (data: any) => {
    router.push(`/restaurant?id=${data}`);
  };

  if (!restaurantList || restaurantList.length === 0) return null;

  return (
    <div className="max-w-7xl mx-auto py-8 px-4">
      <div className="mb-8">
        <div className="flex items-center justify-center gap-2 mb-2">
          <h2 className="font-bold mb-2 text-h4 sm:text-h3 md:text-h2 lg:text-h1">
            <span className="text-primary">Quick Picks</span> For You
          </h2>
          <span className="text-h4 sm:text-h3 md:text-h2 lg:text-h1">😋</span>
        </div>
        <p className="text-center text-gray-600 text-p2 sm:text-p1 md:text-h6 lg:text-h5">
          Curated Just for You: Quick and Delicious Picks to Satisfy Your Cravings
        </p>
      </div>

      <div>
        <Swiper
          slidesPerView={3}
          spaceBetween={30}
          navigation={true}
          modules={[Navigation]}
          className="mySwiper"
        >
          {restaurantList?.length > 0 && restaurantList.map((item: any) => (
            <SwiperSlide onClick={() => handleSelect(item._id)} key={item._id}>
              <CategoryCard
                image={item.image ? BUCKET_ROOT + item.image : BUCKET_ROOT + item.uploadRestaurantPhotos[0]}
                title={item.restaurant_name}
                count={item.count}
              />
            </SwiperSlide>
          ))}
        </Swiper>
      </div>
    </div>
  );
};


export default QuickPicks;