"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 { ChevronLeft, ChevronRight } from "lucide-react";
import apis from "@/utils/apis";
import { getValidImage } from "@/lib/utils";
import { useRouter } from "next/navigation";

interface ExploreCuisinesProps {
    onSelectCuisine?: (cuisineId: string) => void;
}

const ExploreCuisines: React.FC<ExploreCuisinesProps> = ({ onSelectCuisine }) => {
    const router = useRouter();
    const [cuisines, setCuisines] = useState<any[]>([]);
    const [loading, setLoading] = useState<boolean>(true);

    const fetchCuisines = async () => {
        try {
            setLoading(true);
            const response = await apis.restaurant.getCuisines("page=1&limit=100");
            const list = response?.data || response?.data?.data || [];
            setCuisines(Array.isArray(list) ? list : []);
        } catch (error) {
            console.error("Error fetching cuisines:", error);
            setCuisines([]);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchCuisines();
    }, []);

    if (!loading && cuisines.length === 0) {
        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">
                    Explore Cuisines
                </h2>
                {cuisines.length > 3 && (
                    <div className="flex items-center gap-2">
                        <button className="cuisines-prev 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="cuisines-next 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-gray-200 rounded-3xl h-52 animate-pulse" />
                    ))}
                </div>
            ) : (
                <Swiper
                    modules={[Navigation]}
                    navigation={{
                        prevEl: ".cuisines-prev",
                        nextEl: ".cuisines-next",
                    }}
                    spaceBetween={20}
                    slidesPerView={1.2}
                    breakpoints={{
                        640: { slidesPerView: 2.2, spaceBetween: 20 },
                        768: { slidesPerView: 3, spaceBetween: 24 },
                        1024: { slidesPerView: 4, spaceBetween: 24 },
                    }}
                    className="py-2"
                >
                    {cuisines.map((cuisine) => {
                        const imageSrc = getValidImage(cuisine.image);

                        return (
                            <SwiperSlide key={cuisine._id}>
                                <div
                                    onClick={() => {
                                        if (onSelectCuisine) {
                                            onSelectCuisine(cuisine._id);
                                        } else {
                                            router.push(`/search?type=dishes&search=${encodeURIComponent(cuisine.name)}`);
                                        }
                                    }}
                                    className="group relative h-48 sm:h-52 md:h-56 rounded-3xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 cursor-pointer bg-gray-100"
                                >
                                    {/* Image */}
                                    <img
                                        src={imageSrc}
                                        alt={cuisine.name}
                                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                                    />

                                    {/* Gradient Overlay */}
                                    <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/30 to-transparent flex items-end p-5 sm:p-6">
                                        <h3 className="font-bold text-white text-xl sm:text-2xl tracking-tight leading-snug drop-shadow-md">
                                            {cuisine.name}
                                        </h3>
                                    </div>
                                </div>
                            </SwiperSlide>
                        );
                    })}
                </Swiper>
            )}
        </div>
    );
};

export default ExploreCuisines;
