"use client";

import React, { useEffect, useState } from "react";
import DashboardLayout from "@/components/layout/DashboardLayout";
import { Star, MapPin, ChevronLeft, ChevronRight, X, Search } 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, Navigation } 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";

import QuickServiceCards from "@/components/QuickServiceCards/page";
import PopularRestaurants from "@/components/PopularRestaurants/PopularRestaurants";
import ExploreCuisines from "@/components/ExploreCuisines/ExploreCuisines";
import HomePageBanner from "@/components/HomePageBanner/HomePageBanner";
import NearbyStores from "@/components/NearbyStores/NearbyStores";
import OrderAgain from "@/components/OrderAgain/OrderAgain";

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

    const [restaurants, setRestaurants] = useState<any[]>([]);
    const [services, setServices] = useState<any[]>([]);
    const [allServices, setAllServices] = useState<any[]>([]);
    const [selectedService, setSelectedService] = useState<string | null>(null);
    const [loading, setLoading] = useState<boolean>(true);
    const [servicesLoading, setServicesLoading] = useState<boolean>(true);
    const [allServicesLoading, setAllServicesLoading] = useState<boolean>(false);
    const [showAllCategories, setShowAllCategories] = useState<boolean>(false);
    const [categorySearchQuery, setCategorySearchQuery] = useState<string>("");

    const [location, setLocation] = useState<{ lat: number; long: number } | null>(null);
    const selectedAddress = useSelector(
        (state: RootState) => state.user.profile.selectedAddress
    );

    const [selectedCategoryId, setSelectedCategoryId] = useState<string | null>(null);
    const [pageNumber, setPageNumber] = useState(1);
    const [totalPages, setTotalPages] = useState(1);
    const limit = 9;

    useEffect(() => {
        const fetchDefaultCategory = async () => {
            const saved = localStorage.getItem("selectedParentCategory");
            if (saved) {
                setSelectedCategoryId(saved);
            } else {
                try {
                    const response = await apis.ParentCategory.getParnetCategory();
                    const categories = response.data?.data || response.data || [];
                    if (categories.length > 0) {
                        const foodCategory = categories.find((cat: any) => cat.slug === "food");
                        const defaultId = foodCategory ? foodCategory._id : categories[0]._id;
                        setSelectedCategoryId(defaultId);
                        localStorage.setItem("selectedParentCategory", defaultId);
                    } else {
                        setLoading(false);
                    }
                } catch (error) {
                    console.error("Error fetching default parent category:", error);
                    setLoading(false);
                }
            }
        };
        fetchDefaultCategory();
    }, []);

    const getServices = async () => {
        try {
            setServicesLoading(true);
            const apiRes = await apis.category.getCustomerCategories("type=food&page=1&limit=10");
            const rawList = Array.isArray(apiRes?.data)
                ? apiRes.data
                : Array.isArray(apiRes)
                ? apiRes
                : [];
            setServices(rawList);
        } catch (error) {
            console.error("GetServices error:", error);
        } finally {
            setServicesLoading(false);
        }
    };

    const getAllServices = async () => {
        try {
            setAllServicesLoading(true);
            const apiRes = await apis.category.getCustomerCategories("type=food&page=1&limit=100");
            const rawList = Array.isArray(apiRes?.data)
                ? apiRes.data
                : Array.isArray(apiRes)
                ? apiRes
                : [];
            setAllServices(rawList);
        } catch (error) {
            console.error("GetAllServices error:", error);
        } finally {
            setAllServicesLoading(false);
        }
    };

    const handleToggleSeeAll = () => {
        setShowAllCategories(true);
        if (allServices.length === 0) {
            getAllServices();
        }
    };

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

    const getRes = async (page = 1) => {
        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,
                    type: 'food',
                    ...(selectedService && selectedService !== "all" ? { category: selectedService } : {}),
                };

                const apiRes = await apis.restaurant.getAll(params.toString(), payload);

                setRestaurants(apiRes?.data || []);
                setTotalPages(Math.ceil((apiRes?.data_count || 0) / limit));
                setLoading(false);
            };

            if (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 lat = coords.latitude;
                        const long = coords.longitude;
                        setLocation({ lat, long });
                        fetchRestaurants(lat, long);
                    },
                    (error) => {
                        console.error("Geolocation error:", error);
                        setLoading(false);
                    }
                );
            }
        } catch (error) {
            console.error("GetRes error:", error);
            setLoading(false);
        }
    };


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

    useEffect(() => {
        if (!selectedAddress?.lat) {
            navigator.geolocation.getCurrentPosition(
                ({ coords }) => {
                    setLocation({ lat: coords.latitude, long: coords.longitude });
                },
                (error) => {
                    console.error("Geolocation error:", error);
                    setLoading(false);
                }
            );
        }
    }, []);


    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 Delivery-Only Restaurants Near You
                        </h1>
                        <p className="text-gray-200 text-base md:text-lg max-w-xl">
                            Experience India's vibrant food culture with curated lists of the
                            best restaurants near you.
                        </p>
                    </div>
                </div>
            </div>


            {/* Quick Service Cards */}
            <QuickServiceCards />

            {/* Categories Section */}
            <div className="mb-8 px-4 sm:px-6 lg:px-8 py-6 bg-gray-50/80 rounded-2xl border border-gray-100/80">
                <div className="flex items-center justify-between mb-6">
                    <h2 className="text-2xl sm:text-3xl font-bold text-gray-900 tracking-tight">
                        Categories
                    </h2>
                    <div className="flex items-center gap-3">
                        <button
                            onClick={handleToggleSeeAll}
                            className="text-sm sm:text-base font-semibold text-primary hover:text-primary/80 transition-colors cursor-pointer"
                        >
                            See All
                        </button>
                        <div className="flex items-center gap-2">
                            <button
                                className="food-cat-prev w-9 h-9 rounded-full bg-white border border-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-100 transition-all disabled:opacity-30 shadow-sm cursor-pointer"
                                aria-label="Previous category"
                            >
                                <ChevronLeft className="w-5 h-5 text-gray-700" />
                            </button>
                            <button
                                className="food-cat-next w-9 h-9 rounded-full bg-primary flex items-center justify-center text-white hover:bg-primary/90 transition-all disabled:opacity-30 shadow-sm cursor-pointer"
                                aria-label="Next category"
                            >
                                <ChevronRight className="w-5 h-5 text-white" />
                            </button>
                        </div>
                    </div>
                </div>

                {servicesLoading ? (
                    <div className="flex gap-6 overflow-hidden py-2">
                        {Array.from({ length: 10 }).map((_, i) => (
                            <div key={i} className="flex flex-col items-center gap-2 animate-pulse flex-1">
                                <div className="w-18 h-18 sm:w-20 sm:h-20 rounded-full bg-gray-200" />
                                <div className="h-4 w-12 bg-gray-200 rounded" />
                            </div>
                        ))}
                    </div>
                ) : (
                    <Swiper
                        modules={[Navigation]}
                        spaceBetween={16}
                        slidesPerView={4}
                        breakpoints={{
                            320: { slidesPerView: 3.5, spaceBetween: 12 },
                            480: { slidesPerView: 4.5, spaceBetween: 16 },
                            640: { slidesPerView: 6, spaceBetween: 16 },
                            768: { slidesPerView: 8, spaceBetween: 18 },
                            1024: { slidesPerView: 10, spaceBetween: 16 },
                        }}
                        navigation={{
                            prevEl: ".food-cat-prev",
                            nextEl: ".food-cat-next",
                        }}
                        className="py-4 px-1"
                    >
                        {/* Dynamic Category Slides */}
                        {services?.map((service) => {
                            const isAll =
                                service._id === "all" ||
                                service?.category_name?.toLowerCase() === "all";

                            const isSelected = isAll
                                ? selectedService === null ||
                                  selectedService === "all" ||
                                  selectedService === service._id
                                : selectedService === service._id ||
                                  selectedService === service.category_name;

                            const imgSrc =
                                isAll && (!service?.category_image || service.category_image.trim() === "")
                                    ? "https://images.unsplash.com/photo-1568901346375-23c9450c58cd?auto=format&fit=crop&w=300&q=80"
                                    : getValidImage(service?.category_image);

                            return (
                                <SwiperSlide key={service._id}>
                                    <div
                                        className="flex flex-col items-center cursor-pointer group select-none w-full py-1.5"
                                        onClick={() => {
                                            if (isAll) {
                                                setSelectedService(null);
                                            } else {
                                                setSelectedService(service._id);
                                            }
                                        }}
                                    >
                                        <div
                                            className={`w-18 h-18 sm:w-20 sm:h-20 rounded-full flex items-center justify-center transition-all duration-300 ${
                                                isSelected
                                                    ? "p-[3px] border-2 border-primary shadow-md scale-105"
                                                    : "border border-gray-200 group-hover:border-primary/50 group-hover:scale-105"
                                            }`}
                                        >
                                            <div className="w-full h-full rounded-full overflow-hidden">
                                                <img
                                                    src={imgSrc}
                                                    alt={service?.category_name}
                                                    className="w-full h-full object-cover"
                                                />
                                            </div>
                                        </div>
                                        <span
                                            className={`text-xs sm:text-sm mt-2 font-medium transition-colors text-center line-clamp-1 w-full ${
                                                isSelected
                                                    ? "text-primary font-bold"
                                                    : "text-gray-700 group-hover:text-primary"
                                            }`}
                                        >
                                            {service?.category_name}
                                        </span>
                                    </div>
                                </SwiperSlide>
                            );
                        })}
                    </Swiper>
                )}
            </div>

            {/* All Categories Modal Popup */}
            {showAllCategories && (
                <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
                    <div className="bg-white rounded-3xl shadow-2xl max-w-4xl w-full max-h-[85vh] overflow-hidden flex flex-col animate-in fade-in zoom-in-95 duration-200">
                        {/* Header */}
                        <div className="p-5 sm:p-6 border-b border-gray-100 flex items-center justify-between gap-4">
                            <div>
                                <h3 className="text-xl sm:text-2xl font-bold text-gray-900">All Categories</h3>
                                <p className="text-xs sm:text-sm text-gray-500 mt-0.5">Explore all available food categories</p>
                            </div>
                            <div className="flex items-center gap-3">
                                <div className="relative hidden sm:block w-64">
                                    <Search className="w-4 h-4 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
                                    <input
                                        type="text"
                                        placeholder="Search category..."
                                        value={categorySearchQuery}
                                        onChange={(e) => setCategorySearchQuery(e.target.value)}
                                        className="w-full pl-9 pr-4 py-2 bg-gray-100/80 rounded-full text-sm outline-none focus:ring-2 focus:ring-primary/20 text-gray-900"
                                    />
                                </div>
                                <button
                                    onClick={() => {
                                        setShowAllCategories(false);
                                        setCategorySearchQuery("");
                                    }}
                                    className="w-9 h-9 rounded-full bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-600 transition-colors cursor-pointer"
                                >
                                    <X className="w-5 h-5" />
                                </button>
                            </div>
                        </div>

                        {/* Search on mobile */}
                        <div className="px-5 pt-3 sm:hidden">
                            <div className="relative w-full">
                                <Search className="w-4 h-4 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
                                <input
                                    type="text"
                                    placeholder="Search category..."
                                    value={categorySearchQuery}
                                    onChange={(e) => setCategorySearchQuery(e.target.value)}
                                    className="w-full pl-9 pr-4 py-2 bg-gray-100/80 rounded-full text-sm outline-none focus:ring-2 focus:ring-primary/20 text-gray-900"
                                />
                            </div>
                        </div>

                        {/* Content / Grid */}
                        <div className="p-5 sm:p-6 overflow-y-auto flex-grow">
                            {allServicesLoading ? (
                                <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-4 sm:gap-6">
                                    {Array.from({ length: 16 }).map((_, i) => (
                                        <div key={i} className="flex flex-col items-center gap-2 animate-pulse">
                                            <div className="w-18 h-18 sm:w-20 sm:h-20 rounded-full bg-gray-200" />
                                            <div className="h-4 w-12 bg-gray-200 rounded" />
                                        </div>
                                    ))}
                                </div>
                            ) : (
                                <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-4 sm:gap-6">
                                    {allServices
                                        .filter((s) =>
                                            s.category_name?.toLowerCase().includes(categorySearchQuery.toLowerCase())
                                        )
                                        .map((service) => {
                                            const isAll =
                                                service._id === "all" ||
                                                service?.category_name?.toLowerCase() === "all";

                                            const isSelected = isAll
                                                ? selectedService === null ||
                                                  selectedService === "all" ||
                                                  selectedService === service._id
                                                : selectedService === service._id ||
                                                  selectedService === service.category_name;

                                            const imgSrc =
                                                isAll && (!service?.category_image || service.category_image.trim() === "")
                                                    ? "https://images.unsplash.com/photo-1568901346375-23c9450c58cd?auto=format&fit=crop&w=300&q=80"
                                                    : getValidImage(service?.category_image);

                                            return (
                                                <div
                                                    key={service._id}
                                                    className="flex flex-col items-center cursor-pointer group select-none w-full py-1.5"
                                                    onClick={() => {
                                                        if (isAll) {
                                                            setSelectedService(null);
                                                        } else {
                                                            setSelectedService(service._id);
                                                        }
                                                        setShowAllCategories(false);
                                                        setCategorySearchQuery("");
                                                    }}
                                                >
                                                    <div
                                                        className={`w-18 h-18 sm:w-20 sm:h-20 rounded-full flex items-center justify-center transition-all duration-300 ${
                                                            isSelected
                                                                ? "p-[3px] border-2 border-primary shadow-md scale-105"
                                                                : "border border-gray-200 group-hover:border-primary/50 group-hover:scale-105"
                                                        }`}
                                                    >
                                                        <div className="w-full h-full rounded-full overflow-hidden">
                                                            <img
                                                                src={imgSrc}
                                                                alt={service?.category_name}
                                                                className="w-full h-full object-cover"
                                                            />
                                                        </div>
                                                    </div>
                                                    <span
                                                        className={`text-xs sm:text-sm mt-2 font-medium transition-colors text-center line-clamp-1 w-full ${
                                                            isSelected
                                                                ? "text-primary font-bold"
                                                                : "text-gray-700 group-hover:text-primary"
                                                        }`}
                                                    >
                                                        {service?.category_name}
                                                    </span>
                                                </div>
                                            );
                                        })}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            )}

            {/* Popular Restaurants Section */}
            <PopularRestaurants selectedCategoryId={selectedService} />

            {/* Explore Cuisines Section */}
            <ExploreCuisines />

            {/* Vendor Home Page Banner */}
            <HomePageBanner type="food" />

            {/* Nearby Stores Section */}
            <NearbyStores selectedCategoryId={selectedService} />

            {/* Order Again Section */}
            <OrderAgain type="food" />

            {/* Restaurant Grid */}
            <div className="max-w-7xl mx-auto mt-6">
                <h2 className="text-2xl sm:text-3xl font-bold text-gray-900 tracking-tight mb-6">
                    All Restaurants
                </h2>
                {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) => (
                            <Link
                                href={`/restaurant?id=${restaurant._id}`}
                                key={restaurant._id}
                                className="block"
                            >
                                <div className="bg-white shadow-sm hover:shadow-md rounded-xl overflow-hidden flex flex-col">
                                    <div className="relative w-full h-48 overflow-hidden">
                                        <img
                                            src={getValidImage(
                                                restaurant?.image ||
                                                restaurant?.uploadRestaurantPhotos[0]
                                            )}
                                            alt={restaurant?.restaurant_name}
                                            className="w-full h-full object-cover hover:scale-105 duration-300"
                                        />

                                        {Boolean(restaurant?.rating) && Number(restaurant?.rating) > 0 && (
                                            <div className="absolute top-3 left-3 bg-primary 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>

                                    <div className="p-4 flex-1 flex flex-col">
                                        <h3 className="font-semibold text-lg text-gray-900 truncate">
                                            {restaurant?.restaurant_name}
                                        </h3>

                                        <div className="flex justify-between text-gray-600 text-sm mt-2">
                                            <div className="flex items-center truncate max-w-[180px]">
                                                <MapPin size={16} className="mr-1 text-gray-400 flex-shrink-0" />
                                                <span className="truncate">
                                                    {restaurant?.address?.name &&
                                                        restaurant?.address?.city
                                                        ? `${restaurant.address.name}, ${restaurant.address.city}`
                                                        : restaurant?.address?.area ||
                                                        restaurant?.address?.city ||
                                                        "Location unavailable"}
                                                </span>
                                            </div>

                                            <span className="text-gray-500">
                                                {restaurant?.distance?.distance
                                                    ? `Approx ${Number(restaurant.distance.distance).toFixed(1)} km`
                                                    : ""}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </Link>
                        ))}
                    </div>
                ) : (
                    <p className="text-center text-gray-500">No restaurants found.</p>
                )}

                {totalPages > 1 && (
                    <div className="pagination-container">
                        <Pagination>
                            <PaginationPrevious
                                onClick={() => setPageNumber((prev) => Math.max(prev - 1, 1))}
                                className="pagination-btn"
                            />
                            <PaginationContent>
                                {getPaginationRange(pageNumber, totalPages).map((p, i) => (
                                    <PaginationItem key={i}>
                                        {p === "…" ? (
                                            <PaginationEllipsis />
                                        ) : (
                                            <PaginationLink
                                                isActive={pageNumber === p}
                                                onClick={() => setPageNumber(Number(p))}
                                                className={
                                                    pageNumber === p
                                                        ? "pagination-link-active"
                                                        : "pagination-link"
                                                }
                                            >
                                                {p}
                                            </PaginationLink>
                                        )}
                                    </PaginationItem>
                                ))}
                            </PaginationContent>
                            <PaginationNext
                                onClick={() =>
                                    setPageNumber((prev) =>
                                        Math.min(prev + 1, totalPages)
                                    )
                                }
                                className="pagination-btn"
                            />
                        </Pagination>
                    </div>
                )}
            </div>
        </div>
    );
}

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