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

interface OrderAgainProps {
    type?: string;
}

const OrderAgain: React.FC<OrderAgainProps> = ({ type = "food" }) => {
    const router = useRouter();
    const { Toast, userInfo } = useGlobalContext();
    const [orders, setOrders] = useState<any[]>([]);
    const [loading, setLoading] = useState<boolean>(true);

    const navPrevClass = `order-again-prev-${type.replace(/[^a-zA-Z0-9]/g, "")}`;
    const navNextClass = `order-again-next-${type.replace(/[^a-zA-Z0-9]/g, "")}`;

    const fetchOrderAgain = async () => {
        try {
            setLoading(true);
            const params = new URLSearchParams({
                page: "1",
                limit: "100",
            });
            if (type) {
                params.append("type", type);
            }

            const response = await apis.restaurant.getOrderAgain(params.toString());
            const rawList = response?.data || response?.data?.data || [];
            
            if (Array.isArray(rawList)) {
                // Filter out items without restaurant_id and deduplicate by restaurant _id
                const seen = new Set<string>();
                const uniqueRestaurants: any[] = [];

                for (const item of rawList) {
                    const rest = item.restaurant_id || item;
                    if (rest && rest._id && !seen.has(rest._id)) {
                        seen.add(rest._id);
                        uniqueRestaurants.push({
                            ...rest,
                            orderId: item._id || item.order_id,
                        });
                    }
                }
                setOrders(uniqueRestaurants);
            } else {
                setOrders([]);
            }
        } catch (error) {
            console.error("Error fetching order again list:", error);
            setOrders([]);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchOrderAgain();
    }, [userInfo, type]);

    const handleFavourite = async (e: React.MouseEvent, id: string, isFav: boolean) => {
        e.stopPropagation();
        if (!userInfo) {
            Toast.error("Please login to add to favourites");
            return;
        }
        try {
            const payload = {
                restaurant_id: id,
                status: isFav ? "dislike" : "favourite",
            };
            const apiRes = await apis.Favourite.toggle(payload);
            if (apiRes) {
                setOrders((prev) =>
                    prev.map((item) =>
                        item._id === id ? { ...item, is_fav: !isFav } : item
                    )
                );
                Toast.success(isFav ? "Removed from favourites" : "Added to favourites");
            }
        } catch (error) {
            console.error("Error toggling favourite:", error);
        }
    };

    if (!loading && orders.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">
                    Order Again
                </h2>
                {orders.length > 3 && (
                    <div className="flex items-center gap-2">
                        <button className={`${navPrevClass} 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={`${navNextClass} 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-white rounded-2xl p-3 border border-gray-100 animate-pulse">
                            <div className="w-full h-44 bg-gray-200 rounded-xl mb-3" />
                            <div className="h-5 bg-gray-200 rounded w-3/4 mb-2" />
                            <div className="h-4 bg-gray-200 rounded w-1/2" />
                        </div>
                    ))}
                </div>
            ) : (
                <Swiper
                    modules={[Navigation]}
                    navigation={{
                        prevEl: `.${navPrevClass}`,
                        nextEl: `.${navNextClass}`,
                    }}
                    spaceBetween={20}
                    slidesPerView={1.15}
                    breakpoints={{
                        640: { slidesPerView: 2.2, spaceBetween: 20 },
                        768: { slidesPerView: 3, spaceBetween: 24 },
                        1024: { slidesPerView: 4, spaceBetween: 24 },
                    }}
                    className="py-2"
                >
                    {orders.map((restaurant) => {
                        const prepTime = restaurant.average_preparing_time
                            ? `${Math.max(restaurant.average_preparing_time - 5, 5)}-${restaurant.average_preparing_time} mins`
                            : null;

                        const imageSrc = getValidImage(
                            restaurant.image ||
                            (restaurant.uploadRestaurantPhotos && restaurant.uploadRestaurantPhotos[0])
                        );

                        return (
                            <SwiperSlide key={restaurant._id}>
                                <div
                                    onClick={() => {
                                        if (type === "food") {
                                            router.push(`/restaurant?id=${restaurant._id}`);
                                        } else {
                                            router.push(`/grocery/${restaurant._id}?type=${type}`);
                                        }
                                    }}
                                    className="group bg-white rounded-2xl overflow-hidden border border-gray-100 shadow-sm hover:shadow-md transition-all duration-300 cursor-pointer flex flex-col h-full"
                                >
                                    {/* Image Container */}
                                    <div className="relative w-full h-44 sm:h-48 overflow-hidden bg-gray-100">
                                        <img
                                            src={imageSrc}
                                            alt={restaurant.restaurant_name}
                                            className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                                        />
                                        {/* Heart Icon */}
                                        <button
                                            onClick={(e) => handleFavourite(e, restaurant._id, !!restaurant.is_fav)}
                                            className="absolute top-3 right-3 w-8 h-8 rounded-full bg-white/90 hover:bg-white backdrop-blur-sm shadow-sm flex items-center justify-center transition-transform hover:scale-110 active:scale-95"
                                        >
                                            <Heart
                                                className={`w-4 h-4 transition-colors ${
                                                    restaurant.is_fav
                                                        ? "fill-red-500 text-red-500"
                                                        : "text-gray-600 hover:text-red-500"
                                                }`}
                                            />
                                        </button>
                                    </div>

                                    {/* Info Section */}
                                    <div className="p-4 flex flex-col justify-between flex-grow">
                                        <div>
                                            <h3 className="font-bold text-gray-900 text-base sm:text-lg truncate group-hover:text-primary transition-colors text-left">
                                                {restaurant.restaurant_name}
                                            </h3>

                                            <div className="flex items-center justify-between mt-2 text-sm text-gray-600">
                                                {prepTime ? (
                                                    <div className="flex items-center gap-1">
                                                        <Clock className="w-4 h-4 text-gray-400" />
                                                        <span>{prepTime}</span>
                                                    </div>
                                                ) : (
                                                    <div />
                                                )}

                                                {/* Rating Pill */}
                                                {Boolean(restaurant.rating) && Number(restaurant.rating) > 0 && (
                                                    <div className="bg-primary text-white font-bold px-2 py-0.5 rounded-full text-xs flex items-center gap-1 shadow-sm">
                                                        <Star className="w-3 h-3 fill-white" />
                                                        <span>{Number(restaurant.rating).toFixed(1)}</span>
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </SwiperSlide>
                        );
                    })}
                </Swiper>
            )}
        </div>
    );
};

export default OrderAgain;
