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

interface FoodItem {
  id: string;
  title: string;
  price: string;
  discounted_price?: string;
  rating: string;
  image: string;
  restaurantId: {
    _id: string;
    restaurant_name?: string;
  };
  _id: string;
}

interface FoodRecommendationProps {
  selectedCategoryId: string | null;
}

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

  useEffect(() => {
    const fetchRecommendations = async () => {
      try {
        const params = new URLSearchParams({
          category: selectedCategoryId || ''
        });
        const response = await apis.restaurant.getRecommendation(params);
        const result = response.result || [];

        const mappedData: FoodItem[] = result.map((item: any) => ({
          id: item?.food_id,
          title: item?.food_name,
          price: `${currency}${item?.price}`,
          discounted_price: item?.discounted_price ? `${currency}${item?.discounted_price}` : undefined,
          rating: `${item?.food_rating}`,
          image: item?.food_images?.[0] ? `${BUCKET_ROOT}${item?.food_images[0]}` : "",
          restaurantId: item?.restaurant_id,
          _id: item.food_id,
        }));

        setRecommendations(mappedData);
      } catch (error) {
        setError("Failed to load recommendations.");
      }
    };

    fetchRecommendations();
  }, [selectedCategoryId]);

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

  const getBreakpoints = () => {
    const dataLength = recommendations.length;

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

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

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

  if (recommendations.length === 0) {
    return null;
  }

  return (
    <>
      <div className="mb-8 text-center">
        <h2 className="font-bold text-h4 sm:text-h3 md:text-h2 lg:text-h1">
          <span className="text-primary">Food</span> Recommendations
        </h2>

        {/* <p className="text-center text-gray-600 text-p2 sm:text-p1 md:text-h6 lg:text-h5">
          Explore your previously ordered list
        </p> */}

      </div>

      {recommendations.length === 0 ? (
        <div className="text-center py-8">
          <p className="text-gray-500">No recommendations available</p>
        </div>
      ) : recommendations.length === 1 ? (
        <div className="max-w-7xl mx-auto py-2 px-4">
          <div className="flex justify-center">
            <div className="max-w-md w-full">
              <div
                className="flex bg-white rounded-lg shadow-sm border overflow-hidden cursor-pointer"
                onClick={() =>
                  handleCardClick(recommendations[0].restaurantId._id)
                }
              >
                <div className="w-28 h-28 flex-shrink-0 rounded-l-lg overflow-hidden bg-gray-100">
                  <img
                    src={getValidImage(recommendations[0].image)}
                    alt={`Image of ${recommendations[0].title}`}
                    className="w-full h-full object-cover"
                  />
                </div>

                <div className="p-3 flex flex-col justify-between w-full">
                  <div>
                    <h3 className="text-base font-semibold text-black-800">
                      {recommendations[0]?.title}
                    </h3>
                    <p className="text-sm text-neutral-900 font-bold">
                      {recommendations[0]?.discounted_price
                        ? recommendations[0]?.discounted_price
                        : recommendations[0]?.price}
                    </p>
                    <p className="text-sm text-black-600 mt-1">
                      ⭐ {recommendations[0]?.rating}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      ) : (
        <div className="max-w-7xl mx-auto py-2 px-4">
          <Swiper
            slidesPerView={1}
            spaceBetween={15}
            pagination={shouldUsePagination ? { clickable: true } : false}
            loop={shouldUseLoop}
            breakpoints={getBreakpoints()}
            modules={shouldUsePagination ? [Pagination] : []}
            className="mySwiper nearby-swiper"
          >
            {recommendations.map((item) => (
              <SwiperSlide key={item.id}>
                <div
                  className="flex bg-white rounded-lg shadow-sm border overflow-hidden cursor-pointer"
                  onClick={() => handleCardClick(item.restaurantId._id)}
                >
                  <div className="w-28 h-28 flex-shrink-0 rounded-l-lg overflow-hidden bg-gray-100">
                    <img
                      src={getValidImage(item.image)}
                      alt={`Image of ${item.title}`}
                      className="w-full h-full object-cover"
                    />
                  </div>

                  <div className="p-3 flex flex-col justify-between w-full">
                    <div>
                      <h3 className="text-base font-semibold text-black-800">
                        {item?.title}
                      </h3>
                      <p className="text-sm text-neutral-900 font-bold">
                        {item?.discounted_price
                          ? item?.discounted_price
                          : item?.price}
                      </p>
                      <p className="text-sm text-black-600 mt-1">
                        ⭐ {item?.rating}
                      </p>
                    </div>
                  </div>
                </div>
              </SwiperSlide>
            ))}
          </Swiper>
        </div>
      )}
    </>
  );
};

export default FoodRecommendation;
