"use client";

import React, { useEffect, useState, useCallback } from "react";
import DashboardLayout from "@/components/layout/DashboardLayout";
import { Star, MapPin, ChevronLeft, ChevronRight } from "lucide-react";
import GroceryBanner from "@/assets/images/GroceryBanner.png";
import { currency, getValidImage } from "@/lib/utils";
import apis, { BUCKET_ROOT } from "@/utils/apis";
import { logEvent } from "@/utils/analytics";
import CategoriesSection from "@/components/CategoriesSection/CategoriesSection";
import PopularRestaurants from "@/components/PopularRestaurants/PopularRestaurants";
import HomePageBanner from "@/components/HomePageBanner/HomePageBanner";
import NearbyStores from "@/components/NearbyStores/NearbyStores";
import OrderAgain from "@/components/OrderAgain/OrderAgain";

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 { useGlobalContext } from "@/context/Provider";
import CartSidebar, { CartItem } from "@/components/grocery/CartSidebar";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";

function FoodDelivery() {
    const router = useRouter();
    const { Toast } = useGlobalContext();
    const orange = "hsl(var(--brand-500))";
    const categoryScrollRef = React.useRef<HTMLDivElement>(null);

    const handleScroll = (direction: "left" | "right") => {
        if (categoryScrollRef.current) {
            const scrollAmount = 400;
            categoryScrollRef.current.scrollBy({
                left: direction === "left" ? -scrollAmount : scrollAmount,
                behavior: "smooth",
            });
        }
    };

    const selectedAddress = useSelector(
        (state: RootState) => state.user.profile.selectedAddress
    );

    const [restaurants, setRestaurants] = useState<any[]>([]);
    const [loading, setLoading] = useState<boolean>(true);
    const [location, setLocation] = useState<{ lat: number; long: number } | null>(
        null
    );
    const [pageNumber, setPageNumber] = useState(1);
    const [totalPages, setTotalPages] = useState(1);
    const limit = 9;

    const [cartItems, setCartItems] = useState<CartItem[]>([]);
    const [isCartOpen, setIsCartOpen] = useState(false);
    const [isInitialized, setIsInitialized] = useState(false);
    const [bannerList, setBannerList] = useState<any[]>([]);

    const [parentCategories, setParentCategories] = useState<any[]>([]);
    const [selectedParentCategoryId, setSelectedParentCategoryId] = useState<string>("");
    const [parentCategoriesLoading, setParentCategoriesLoading] = useState<boolean>(true);
    const [selectedSubCategoryId, setSelectedSubCategoryId] = useState<string | null>(null);

    const getBanners = async (categoryId = selectedParentCategoryId, categoriesList = parentCategories) => {
        if (!categoryId) return;
        try {
            let latitude = null;
            let longitude = null;

            if (selectedAddress?.lat && selectedAddress?.long) {
                latitude = parseFloat(selectedAddress.lat);
                longitude = parseFloat(selectedAddress.long);
            } else {
                const position = await new Promise<GeolocationPosition>(
                    (resolve, reject) =>
                        navigator.geolocation.getCurrentPosition(resolve, reject)
                );
                latitude = position.coords.latitude;
                longitude = position.coords.longitude;
            }

            const selectedCat = categoriesList.find(c => c._id === categoryId);
            const bannerType = selectedCat?.type;

            const params = new URLSearchParams({
                lat: latitude.toString(),
                long: longitude.toString(),
                type: bannerType,
            });

            const res = await apis.Banner.getBanner(params.toString());
            setBannerList(res || []);
        } catch (error) {
            console.error("Banner fetch error:", error);
        }
    };

    useEffect(() => {
        const savedCart = localStorage.getItem('groceryCartItems');
        if (savedCart) {
            setCartItems(JSON.parse(savedCart));
        }
        setIsInitialized(true);

        const handleToggle = () => setIsCartOpen(prev => !prev);
        window.addEventListener('toggle-grocery-cart', handleToggle);
        return () => window.removeEventListener('toggle-grocery-cart', handleToggle);
    }, []);

    useEffect(() => {
        if (!isInitialized) return;
        localStorage.setItem('groceryCartItems', JSON.stringify(cartItems));
        window.dispatchEvent(new CustomEvent('grocery-cart-updated', { detail: cartItems.length }));
    }, [cartItems, isInitialized]);

    const addToCart = useCallback((product: any) => {
        const productId = product._id || product.id;
        const hasDiscount = (product.is_discount_active !== false) &&
            product.discounted_price !== undefined &&
            product.discounted_price !== null &&
            Number(product.discounted_price) > 0 &&
            Number(product.discounted_price) < Number(product.price);

        const effectivePrice = hasDiscount ? Number(product.discounted_price) : Number(product.price || product.base_price || product.original_price || 0);

        logEvent("add_to_cart", {
            currency: "INR",
            value: effectivePrice,
            items: [{
                item_id: productId,
                item_name: product.name || product.title,
                price: effectivePrice,
                quantity: 1,
                item_category: "grocery"
            }]
        });

        setCartItems(prev => {
            const productId = product._id || product.id;
            const existing = prev.find(item => item.id === productId);
            if (existing) {
                return prev.map(item =>
                    item.id === productId ? { ...item, quantity: item.quantity + 1 } : item
                );
            }
            return [...prev, { ...product, id: productId, price: `${currency}${effectivePrice}.00`, originalPrice: hasDiscount ? `${currency}${product.price}.00` : undefined, quantity: 1, totalStock: product.total_stock }];
        });
    }, []);

    const removeFromCart = useCallback((productId: string | number) => {
        setCartItems(prev => {
            const existing = prev.find(item => item.id === productId);
            if (existing && existing.quantity > 1) {
                return prev.map(item =>
                    item.id === productId ? { ...item, quantity: item.quantity - 1 } : item
                );
            }
            return prev.filter(item => item.id !== productId);
        });
    }, []);

    const deleteItem = useCallback((productId: string | number) => {
        setCartItems(prev => prev.filter(item => item.id !== productId));
    }, []);

    const getRes = async (
        page = 1,
        categoryId = selectedParentCategoryId,
        categoryType = "grocery",
        subCatId = selectedSubCategoryId
    ) => {
        if (!categoryId) return;
        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: categoryType,
                    ...(subCatId && subCatId !== "all" ? { category: subCatId } : {}),
                };

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

                setRestaurants(apiRes?.data || []);
                if (apiRes?.deliveryFeeOptions) {
                    localStorage.setItem("grocery_delivery_fee_options", apiRes.deliveryFeeOptions);
                }
                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(() => {
        const fetchParentCategories = async () => {
            try {
                setParentCategoriesLoading(true);
                const response = await apis.ParentCategory.getParnetCategory();
                const categories = response?.data || [];
                const filtered = categories.filter(
                    (cat: any) =>
                        cat.slug?.toLowerCase() !== "food" &&
                        cat.type?.toLowerCase() !== "food" &&
                        cat.name?.toLowerCase() !== "food"
                );
                setParentCategories(filtered);
                if (filtered.length > 0) {
                    const defaultCat = filtered.find(
                        (cat: any) =>
                            cat.slug?.toLowerCase() === "grocery" ||
                            cat.type?.toLowerCase() === "grocery"
                    ) || filtered[0];
                    setSelectedParentCategoryId(defaultCat._id);
                    const defaultType = defaultCat.type;
                    getRes(1, defaultCat._id, defaultType, null);
                    getBanners(defaultCat._id, filtered);
                }
            } catch (error) {
                console.error("Error fetching parent categories:", error);
            } finally {
                setParentCategoriesLoading(false);
            }
        };
        fetchParentCategories();
    }, []);

    useEffect(() => {
        if (selectedParentCategoryId) {
            const selectedCat = parentCategories.find(c => c._id === selectedParentCategoryId);
            getRes(pageNumber, selectedParentCategoryId, selectedCat?.type, selectedSubCategoryId);
        }
    }, [pageNumber]);

    useEffect(() => {
        if (selectedParentCategoryId) {
            const selectedCat = parentCategories.find(c => c._id === selectedParentCategoryId);
            getRes(1, selectedParentCategoryId, selectedCat?.type, selectedSubCategoryId);
            getBanners(selectedParentCategoryId, parentCategories);
            setPageNumber(1);
        }
    }, [selectedAddress]);

    const handleCategoryChange = (categoryId: string) => {
        setSelectedParentCategoryId(categoryId);
        setSelectedSubCategoryId(null);
        setPageNumber(1);
        const selectedCat = parentCategories.find(c => c._id === categoryId);
        const catType = selectedCat?.type;
        getRes(1, categoryId, catType, null);
        getBanners(categoryId, parentCategories);
    };

    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="relative overflow-x-hidden min-h-screen bg-gray-50">
            <div className={`p-5 transition-all duration-300 ${isCartOpen ? 'me-[400px]' : ''}`}>
                {/* Hero Banner */}
                <div className="relative mb-8 rounded-2xl overflow-hidden">
                    <div
                        className="bg-gradient-to-r rtl:bg-gradient-to-l 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(${GroceryBanner?.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">
                                Pharmacy, Grocery & Food Delivered Fast
                            </h1>
                            <p className="text-gray-200 text-base md:text-lg max-w-xl">
                                Groceries, medicines, and daily essentials delivered fresh and on time.                            </p>
                        </div>
                    </div>
                </div>

                {/* Circular Category Selector */}
                {parentCategories.length > 0 && (
                    <div className="max-w-7xl mx-auto mb-8 bg-white p-6 rounded-2xl border border-gray-100 shadow-sm">
                        <div className="mb-5 flex justify-between items-center">
                            <h3 className="text-lg font-bold text-gray-900">Shop by Category</h3>
                            <div className="flex gap-2 select-none">
                                <button
                                    onClick={() => handleScroll('left')}
                                    className="w-8 h-8 rounded-full border border-gray-200 flex items-center justify-center bg-white hover:bg-gray-50 hover:border-gray-300 text-gray-600 active:bg-gray-100 transition-all shadow-sm"
                                    aria-label="Scroll Left"
                                >
                                    <ChevronLeft size={16} />
                                </button>
                                <button
                                    onClick={() => handleScroll('right')}
                                    className="w-8 h-8 rounded-full border border-gray-200 flex items-center justify-center bg-white hover:bg-gray-50 hover:border-gray-300 text-gray-600 active:bg-gray-100 transition-all shadow-sm"
                                    aria-label="Scroll Right"
                                >
                                    <ChevronRight size={16} />
                                </button>
                            </div>
                        </div>
                        <div
                            ref={categoryScrollRef}
                            className="flex gap-6 sm:gap-8 items-center overflow-x-auto py-3 px-2 select-none scroll-smooth"
                            style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
                        >
                            {parentCategories.map((cat) => {
                                const isSelected = selectedParentCategoryId === cat._id;
                                return (
                                    <div
                                        key={cat._id}
                                        onClick={() => handleCategoryChange(cat._id)}
                                        className="flex flex-col items-center justify-center cursor-pointer group flex-shrink-0"
                                    >
                                        <div className={`w-20 h-20 sm:w-24 sm:h-24 rounded-full overflow-hidden flex items-center justify-center bg-white shadow-sm border transition-all duration-300 ${isSelected ? 'border-brand-500 ring-4 ring-brand-500/10 scale-105 shadow-md' : 'border-gray-100 group-hover:scale-105 group-hover:shadow-md'}`}>
                                            <img
                                                src={getValidImage(cat.image || cat.category_image)}
                                                alt={cat.name || "Category"}
                                                className="w-full h-full object-cover"
                                            />
                                        </div>
                                        <span className={`mt-2.5 text-xs sm:text-sm font-semibold tracking-wide transition-colors capitalize ${isSelected ? 'text-brand-600' : 'text-gray-600 group-hover:text-brand-600'}`}>
                                            {cat.name}
                                        </span>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                )}

                {/* Categories Section Component */}
                <CategoriesSection
                    categoryType={parentCategories.find(c => c._id === selectedParentCategoryId)?.type}
                    selectedCategoryId={selectedSubCategoryId}
                    onSelectCategory={(subCatId) => {
                        setSelectedSubCategoryId(subCatId);
                        const selectedCat = parentCategories.find(c => c._id === selectedParentCategoryId);
                        getRes(1, selectedParentCategoryId, selectedCat?.type, subCatId);
                    }}
                />

                {/* Popular Stores Section */}
                <PopularRestaurants
                    categoryType={parentCategories.find(c => c._id === selectedParentCategoryId)?.type}
                    selectedCategoryId={selectedSubCategoryId}
                    title="Popular Store"
                />

                {/* Vendor Home Page Banner */}
                <HomePageBanner
                    type={parentCategories.find(c => c._id === selectedParentCategoryId)?.type || "grocery"}
                />

                {/* Nearby Stores Section */}
                <NearbyStores
                    categoryType={parentCategories.find(c => c._id === selectedParentCategoryId)?.type}
                    selectedCategoryId={selectedSubCategoryId}
                    title="Nearby Stores"
                />

                {/* Order Again Section */}
                <OrderAgain
                    type={parentCategories.find(c => c._id === selectedParentCategoryId)?.type}
                />


                {/* Header Section */}
                <div className="max-w-7xl mx-auto mb-6">
                    <h2 className="text-2xl sm:text-3xl font-bold text-gray-900 tracking-tight">
                        All Stores
                    </h2>
                </div>

                {/* Restaurant Grid */}
                <div className="max-w-7xl mx-auto">
                    {loading ? (
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                            {[1, 2, 3, 4, 5, 6].map((i) => (
                                <div key={i} className="bg-white rounded-2xl p-3 border border-gray-100 animate-pulse">
                                    <div className="w-full h-48 sm:h-52 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>
                    ) : restaurants.length > 0 ? (
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                            {restaurants?.map((restaurant) => (
                                <Link
                                    href={`/grocery/${restaurant._id}?type=${parentCategories.find(c => c._id === selectedParentCategoryId)?.type || 'grocery'}`}
                                    key={restaurant._id}
                                    className="block"
                                >
                                    <div className="bg-white rounded-2xl p-3 border border-transparent hover:border-gray-200 hover:shadow-lg transition-all duration-300 group flex flex-col h-full">
                                        <div className="relative w-full h-48 sm:h-52 rounded-xl overflow-hidden mb-3">
                                            <img
                                                src={getValidImage(
                                                    restaurant?.image ||
                                                    restaurant?.uploadRestaurantPhotos?.[0]
                                                )}
                                                alt={restaurant?.restaurant_name}
                                                className="w-full h-full object-cover group-hover:scale-[1.02] transition-transform duration-300"
                                            />
                                        </div>

                                        <div className="flex-1 flex flex-col gap-1">
                                            <div className="flex justify-between items-center">
                                                <h3 className="font-bold text-lg text-gray-900 truncate max-w-[80%]">
                                                    {restaurant?.restaurant_name}
                                                </h3>
                                                {Number(restaurant?.rating) > 0 && (
                                                    <div className="bg-green-700 text-white px-2 py-0.5 rounded-lg text-xs font-bold flex items-center gap-0.5 shrink-0">
                                                        {restaurant.rating} <span className="text-[10px]">★</span>
                                                    </div>
                                                )}
                                            </div>

                                            <div className="flex justify-between text-gray-500 text-sm mt-1">
                                                <span className="truncate max-w-[65%] capitalize">
                                                    {parentCategories.find(c => c._id === selectedParentCategoryId)?.name} Store
                                                </span>
                                                <span className="font-semibold text-gray-700 shrink-0">
                                                    {restaurant?.distance?.distance
                                                        ? `Approx ${Number(restaurant.distance.distance).toFixed(1)} km`
                                                        : ""}
                                                </span>
                                            </div>

                                            <div className="flex items-center text-xs text-gray-400 mt-1 truncate">
                                                <MapPin size={14} className="me-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>
                                        </div>
                                    </div>
                                </Link>
                            ))}
                        </div>
                    ) : (
                        <p className="text-center text-gray-500">No stores 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>
            <CartSidebar
                isOpen={isCartOpen}
                onClose={() => setIsCartOpen(false)}
                items={cartItems}
                onAdd={addToCart}
                onRemove={removeFromCart}
                onDeleteItem={deleteItem}
                orange={orange}
                onClearCart={() => setCartItems([])}
            />
        </div>
    );
}

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