"use client";

import React, { useEffect, useState } from "react";
import DashboardLayout from "@/components/layout/DashboardLayout";
import { Star, MapPin, Leaf, Drumstick, Wifi, Clock, Sprout } from "lucide-react";
import DineoutBanner from "@/assets/images/dineoutBanner.png";
import { getValidImage, currency } from "@/lib/utils";
import apis, { BUCKET_ROOT } from "@/utils/apis";
import { Swiper, SwiperSlide } from "swiper/react";
import { Pagination } from "swiper/modules";
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import Link from "next/link";
import { useSelector } from "react-redux";
import { RootState } from "@/store/store";
import { useRouter } from "next/navigation";

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

    const filters = [
        { id: "veg", label: "Pure Veg", icon: <Leaf size={20} /> },
        { id: "non_veg", label: "Non-Veg", icon: <Drumstick size={20} /> },
        { id: "rating_4plus", label: "Rating 4.0+", icon: <Star size={20} /> },
    ];

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

    const getRes = async (customLocation?: { lat: number; long: number }, filter?: string | null, serviceId?: string | null) => {
        try {
            setLoading(true);
            const getAndFetch = async (lat: number, long: number) => {
                const params = new URLSearchParams({
                    page: "1",
                    limit: "20",
                });

                const payload: any = {
                    lat,
                    long,
                    isDineOut: true,
                };
                if (filter === "veg") payload.veg = true;
                if (filter === "non_veg") payload.non_veg = true;
                if (filter === "rating_4plus") payload.rating_4plus = true;
                if (serviceId) payload.service_id = serviceId;

                const apiRes = await apis.restaurant.getAll(params.toString(), payload);
                setRestaurants(apiRes?.data || []);
                setLoading(false);
            };

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

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

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

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

    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 Dining Out Restaurants in India
                        </h1>
                        <p className="text-gray-200 text-base md:text-lg max-w-xl">
                            Experience India's vibrant food culture with our curated list of
                            top restaurants offering authentic flavors, diverse cuisines, and
                            unforgettable dining experiences.
                        </p>
                    </div>
                </div>
            </div>

            {/* Our Services Section */}
            <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">Services</span>
                    </h2>
                </div>
                <div className="relative">
                    <Swiper
                        modules={[Pagination]}
                        spaceBetween={16}
                        slidesPerView={2}
                        pagination={{
                            clickable: true,
                            el: '.services-pagination',
                        }}
                        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">
                                        {/* Image */}
                                        <div className="h-24 w-full rounded-t-2xl overflow-hidden">
                                            <img
                                                src={getValidImage(service?.image)}
                                                alt={service?.name}
                                                className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                                            />
                                        </div>

                                        {/* Label */}
                                        <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?.name}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </SwiperSlide>
                        ))}
                    </Swiper>

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

            {/* Filters Section */}
            <div className="max-w-7xl mx-auto mb-8">
                <div className="overflow-x-auto">
                    <div className="flex gap-3 pb-2 min-w-max">
                        {filters?.map((filter) => (
                            <div
                                key={filter.id}
                                onClick={() =>
                                    setSelectedFilter(selectedFilter === filter.id ? null : filter.id)
                                }
                                className={`flex-shrink-0 px-4 py-2 rounded-full border cursor-pointer transition-all duration-200 flex items-center gap-2 ${selectedFilter === filter.id
                                    ? "bg-brand-500 text-white border-primary shadow-md"
                                    : "bg-white text-gray-700 border-gray-300 hover:border-primary/30 hover:bg-brand-50"
                                    }`}
                            >
                                <div className="flex items-center justify-center w-5 h-5">
                                    {filter.icon}
                                </div>
                                <span className="text-sm font-medium whitespace-nowrap">
                                    {filter.label}
                                </span>
                            </div>
                        ))}
                    </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={`/dineout/${restaurant._id}`} key={restaurant._id} className="block">
                                <div
                                    key={restaurant._id}
                                    className="bg-white shadow-sm hover:shadow-md transition-shadow rounded-xl overflow-hidden flex flex-col"
                                >
                                    {/* Restaurant Image */}
                                    <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"
                                            onError={(e) => {
                                                const target = e.target as HTMLImageElement;
                                                target.src = '/placeholder-restaurant.jpg';
                                            }}
                                        />
                                        {/* Rating Badge */}
                                        {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>

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

                                        {/* Services + per plate */}
                                        <div className="flex justify-between items-center mb-2">
                                            <div className="flex flex-wrap gap-2 text-p1 text-gray-600">
                                                {restaurant?.services?.slice(0, 2)?.map((service: any) => (
                                                    <span
                                                        key={service._id}
                                                        className="bg-gray-100 text-gray-700 px-3 py-1 rounded-full text-xs font-medium"
                                                    >
                                                        {service?.name}
                                                    </span>
                                                ))}
                                            </div>

                                            <div className="text-p1 font-medium text-gray-900 whitespace-nowrap ml-4">
                                                {currency}{restaurant?.estimated_price_per_plate
                                                    ? restaurant.estimated_price_per_plate * 2
                                                    : 'N/A'} for two

                                            </div>
                                        </div>

                                        {/* Amenities */}
                                        <div className="flex flex-wrap gap-2 text-p1 text-gray-600 mb-4">
                                            {restaurant?.amenities?.slice(0, 2)?.map((amenity: any) => (
                                                <span
                                                    key={amenity._id}
                                                    className="bg-gray-100 text-gray-800 px-3 py-1 rounded-full text-xs font-medium border border-gray-200"
                                                >
                                                    {amenity?.name}
                                                </span>
                                            ))}
                                        </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>
                )}
            </div>
        </div>
    );
}

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