"use client";

import React, { useEffect, useState } from "react";
import DashboardLayout from "@/components/layout/DashboardLayout";
import { Star, MapPin } from "lucide-react";
import DineoutBanner from "@/assets/images/dineoutBanner.png";
import { getValidImage } from "@/lib/utils";
import apis from "@/utils/apis";
import { Swiper, SwiperSlide } from "swiper/react";
import { Pagination as SwiperPagination } from "swiper/modules";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";
import Link from "next/link";
import {
    Pagination,
    PaginationContent,
    PaginationLink,
    PaginationItem,
    PaginationPrevious,
    PaginationNext,
    PaginationEllipsis,
} from "@/components/ui/pagination";
import { useSelector } from "react-redux";
import { RootState } from "@/store/store";
import { useRouter } from "next/navigation";

function Catering() {
    const router = useRouter();

    const [restaurants, setRestaurants] = useState<any[]>([]);
    const [services, setServices] = useState<any[]>([]);
    const [selectedService, setSelectedService] = useState<string | null>(null);
    const [loading, setLoading] = useState<boolean>(true);
    const [servicesLoading, setServicesLoading] = useState<boolean>(true);
    const [location, setLocation] = useState<{ lat: number; long: number } | null>(
        null
    );
    const selectedAddress = useSelector(
        (state: RootState) => state.user.profile.selectedAddress
    );
    const [pageNumber, setPageNumber] = useState(1);
    const [totalPages, setTotalPages] = useState(1);
    const limit = 9;

    const getServices = async () => {
        try {
            setServicesLoading(true);
            const apiRes = await apis.category.get();
            if (apiRes?.data) {
                const cateringCategories = apiRes.data.filter(
                    (category: any) => category?.catering_services === true
                );
                setServices(cateringCategories);
            }
        } catch (error) {
            console.error("GetServices error:", error);
        } finally {
            setServicesLoading(false);
        }
    };

    const getRes = async (page = 1, customLocation?: { lat: number; long: number }, serviceId?: string | null) => {
        try {
            setLoading(true);
            const fetchRestaurants = async (lat: number, long: number) => {
                const params = new URLSearchParams({
                    page: String(page),
                    limit: String(limit),
                });
                const payload: any = { lat, long, catering_services: true };
                if (serviceId) payload.service_id = serviceId;
                const apiRes = await apis.restaurant.getAll(params.toString(), payload);
                setRestaurants(apiRes?.data || []);
                setTotalPages(Math.ceil((apiRes?.data_count || 0) / limit));
                setLoading(false);
            };

            if (selectedAddress && selectedAddress.lat && selectedAddress.long) fetchRestaurants(parseFloat(selectedAddress.lat), parseFloat(selectedAddress.long));
            else if (location) fetchRestaurants(location.lat, location.long);
            else {
                navigator.geolocation.getCurrentPosition(
                    ({ coords }) => {
                        const { latitude, longitude } = coords;
                        setLocation({ lat: latitude, long: longitude });
                        fetchRestaurants(latitude, longitude);
                    },
                    (error) => {
                        console.error("Location error:", error);
                        setLoading(false);
                    }
                );
            }
        } catch (error) {
            console.error("GetRes error:", error);
            setLoading(false);
        }
    };

    useEffect(() => {
        getRes(pageNumber, undefined, selectedService);
    }, [pageNumber, selectedService, selectedAddress]);


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

    const handleServiceClick = (serviceId: string) => {
        setSelectedService(prev => prev === serviceId ? null : serviceId);
        setPageNumber(1);
    };

    const getPaginationRange = (currentPage: number, totalPages: number, siblingCount = 1) => {
        const totalPageNumbers = siblingCount * 2 + 5;
        if (totalPages <= totalPageNumbers) return Array.from({ length: totalPages }, (_, i) => i + 1);

        const leftSiblingIndex = Math.max(currentPage - siblingCount, 2);
        const rightSiblingIndex = Math.min(currentPage + siblingCount, totalPages - 1);
        const shouldShowLeftEllipsis = leftSiblingIndex > 2;
        const shouldShowRightEllipsis = rightSiblingIndex < totalPages - 1;

        const range: (number | '...')[] = [1];
        if (shouldShowLeftEllipsis) range.push('...');
        for (let i = leftSiblingIndex; i <= rightSiblingIndex; i++) range.push(i);
        if (shouldShowRightEllipsis) range.push('...');
        range.push(totalPages);
        return range;
    };


    return (
        <div className="min-h-screen bg-gray-50 p-5">
            {/* Hero Banner */}
            <div className="relative mb-8 rounded-2xl overflow-hidden">
                <div
                    className="bg-gradient-to-r from-gray-900 to-gray-700 text-white p-10 md:p-14 bg-center h-80 md:h-[420px] rounded-2xl relative"
                    style={{
                        backgroundImage: `url(${DineoutBanner?.src})`,
                        backgroundBlendMode: "overlay",
                        backgroundSize: "cover",
                        backgroundRepeat: "no-repeat",
                        backgroundPosition: "center",
                    }}
                >
                    <div className="max-w-3xl flex flex-col justify-center h-full">
                        <h1 className="text-3xl md:text-5xl font-bold mb-5 leading-tight">
                            Explore Top Catering Services in India
                        </h1>
                        <p className="text-gray-200 text-base md:text-lg max-w-xl">
                            Experience exceptional dining anywhere with India's finest catering services. From grand weddings and corporate events to intimate gatherings, discover professional caterers offering diverse cuisines, personalized menus, and impeccable service to make every occasion unforgettable.
                        </p>
                    </div>
                </div>
            </div>

            {/* Our Categories Section */}
            {/* {services.length > 0 && (
                <div className="mb-8 px-4">
                    <div className="text-center mb-6">
                        <h2 className="text-h1 font-bold text-gray-900">
                            Our <span className="text-primary">Categories</span>
                        </h2>
                    </div>
                    <div className="relative">
                        <Swiper
                            modules={[SwiperPagination]}
                            spaceBetween={16}
                            slidesPerView={2}
                            pagination={{
                                clickable: true,
                                el: ".services-pagination-catering",
                            }}
                            breakpoints={{
                                480: { slidesPerView: 3 },
                                640: { slidesPerView: 4 },
                                768: { slidesPerView: 5 },
                                1024: { slidesPerView: 6 },
                            }}
                            className="py-2"
                        >
                            {services?.map((service) => (
                                <SwiperSlide key={service._id}>
                                    <div
                                        className={`flex-shrink-0 bg-white rounded-2xl shadow-sm border hover:shadow-md transition-all duration-300 cursor-pointer group h-full ${selectedService === service._id
                                            ? "border-primary ring-2 ring-primary/20 shadow-md"
                                            : "border-gray-100"
                                            }`}
                                        onClick={() => handleServiceClick(service._id)}
                                    >
                                        <div className="h-40 flex flex-col">
                                            
                                            <div className="h-24 w-full rounded-t-2xl overflow-hidden">
                                                <img
                                                    src={getValidImage(service?.category_image)}
                                                    alt={service?.category_name}
                                                    className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                                                />
                                            </div>

                                            
                                            <div className="flex-1 p-3 flex items-center justify-center">
                                                <span className="text-sm font-semibold text-gray-800 text-center leading-tight line-clamp-2">
                                                    {service?.category_name}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </SwiperSlide>
                            ))}
                        </Swiper>

                        
                        <div className="services-pagination-catering flex justify-center gap-1 mt-4"></div>
                    </div>
                </div>
            )} */}

            {/* Restaurant Grid */}
            <div className="max-w-7xl mx-auto">
                {loading ? (
                    <p className="text-center text-gray-500">Loading Vendor/Stores...</p>
                ) : restaurants.length > 0 ? (
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                        {restaurants?.map((restaurant: any) => (
                            <Link
                                href={`/catering/${restaurant._id}`}
                                key={restaurant._id}
                                className="block"
                            >
                                <div className="bg-white shadow-sm hover:shadow-md transition-shadow rounded-xl overflow-hidden flex flex-col">
                                    <div className="relative w-full h-48 overflow-hidden">
                                        <img
                                            src={getValidImage(restaurant?.image ? restaurant?.image : restaurant?.uploadRestaurantPhotos[0])}
                                            alt={restaurant?.restaurant_name}
                                            className="w-full h-full object-cover transition-transform duration-300 hover:scale-105"
                                        />
                                        {Number(restaurant?.rating) > 0 && (
                                            <div className="absolute top-3 left-3 bg-brand-500 text-white px-2 py-1 rounded text-xs font-semibold flex items-center gap-1">
                                                {restaurant?.rating} <Star size={12} fill="white" />
                                            </div>
                                        )}
                                    </div>

                                    {/* Details Section */}
                                    <div className="p-4 flex-1 flex flex-col">
                                        {/* Name */}
                                        <div className="flex justify-between items-start mb-2">
                                            <h3 className="font-semibold text-lg text-gray-900 truncate">
                                                {restaurant?.restaurant_name}
                                            </h3>
                                        </div>

                                        {/* Address + Distance */}
                                        <div className="flex justify-between text-p1 text-gray-600 mb-3">
                                            <div className="relative group flex items-center max-w-[180px] text-p1 text-gray-700">
                                                <MapPin
                                                    size={14}
                                                    className="mr-1 text-gray-400 min-w-[14px]"
                                                />

                                                <div className="truncate max-w-full cursor-default">
                                                    {restaurant?.address?.name && restaurant?.address?.city
                                                        ? `${restaurant.address.name}, ${restaurant.address.city}`
                                                        : restaurant?.address?.area ||
                                                        restaurant?.address?.city ||
                                                        "Location unavailable"}
                                                </div>

                                                {/* Tooltip */}
                                                {restaurant?.address?.name && restaurant?.address?.city && (
                                                    <div className="absolute top-[calc(100%-6px)] left-0 w-max max-w-xs bg-gray-800 text-white text-xs rounded px-3 py-2 shadow-lg opacity-0 group-hover:opacity-100 transition-opacity z-10">
                                                        {`${restaurant.address.name}, ${restaurant.address.city}`}
                                                    </div>
                                                )}
                                            </div>

                                            <div className="text-p1 text-gray-500">
                                                {restaurant?.distance?.distance
                                                    ? `Approx ${Number(restaurant.distance.distance).toFixed(1)} km`
                                                    : "N/A"}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </Link>
                        ))}
                    </div>
                ) : (
                    <p className="text-center text-gray-500">No restaurants found.</p>
                )}
                {totalPages > 1 && (
                    <div className="services-pagination flex justify-center gap-1 mt-4">
                        <Pagination>
                            <PaginationPrevious
                                onClick={() => setPageNumber(prev => Math.max(prev - 1, 1))}
                                className="cursor-pointer"
                            />
                            <PaginationContent>
                                {getPaginationRange(pageNumber, totalPages)?.map((p, i) => (
                                    <PaginationItem key={i}>
                                        {p === '...' ? (
                                            <PaginationEllipsis />
                                        ) : (
                                            <PaginationLink
                                                isActive={pageNumber === p}
                                                onClick={() => setPageNumber(Number(p))}
                                                className="cursor-pointer"
                                            >
                                                {p}
                                            </PaginationLink>
                                        )}
                                    </PaginationItem>
                                ))}
                            </PaginationContent>
                            <PaginationNext
                                onClick={() => setPageNumber(prev => Math.min(prev + 1, totalPages))}
                                className="cursor-pointer"
                            />
                        </Pagination>
                    </div>
                )}
            </div>
        </div>
    );
}

export default function JobAutomationPage() {
    return (
        <DashboardLayout>
            <Catering />
        </DashboardLayout>
    );
}