"use client";

import React, { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { Star, MapPin, Clock, Heart, Phone, Globe } from "lucide-react";
import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
type Swiper = any;
type SwiperSlide = any;
const { Pagination } = require('swiper/modules');
import apis from "@/utils/apis";
import { getTodayStatus, getValidImage, currency } from "@/lib/utils";
import DashboardLayout from "@/components/layout/DashboardLayout";
import TimingsModal from "@/components/TimingsModal/page";
import { useGlobalContext } from "@/context/Provider";
import ImagePreviewModal from "@/components/ImagePreviewModal/page";

const RestaurantDetail = () => {
    const params = useParams();
    const router = useRouter();
    const restaurantId = params.restaurantId;
    const [restaurant, setRestaurant] = useState<any>(null);
    const [loading, setLoading] = useState(true);
    const [selectedImageIndex, setSelectedImageIndex] = useState<number>(0);
    const [isTimingsModalOpen, setIsTimingsModalOpen] = useState(false);
    const [isPreviewOpen, setIsPreviewOpen] = useState(false);
    const [previewImages, setPreviewImages] = useState<any[]>([]);
    const [previewInitialIndex, setPreviewInitialIndex] = useState<number>(0);

    const { userInfo } = useGlobalContext();

    const todayStatus = getTodayStatus(restaurant?.dine_out_working_day);


    useEffect(() => {
        async function fetchRestaurant() {
            try {
                setLoading(true);
                const apiRes = await apis.restaurant.detail(restaurantId, "");
                setRestaurant({
                    ...apiRes?.data,
                    distance: apiRes?.distance,
                    offers: apiRes?.offers,
                });
            } catch (error) {
                console.error("Failed to fetch restaurant", error);
            } finally {
                setLoading(false);
            }
        }

        if (restaurantId) {
            fetchRestaurant();
        }
    }, [restaurantId]);

    const getCurrentDayTimings = () => {
        const today = new Date().toLocaleDateString("en-US", { weekday: "long" });
        const todayTimings = restaurant?.dine_out_working_day?.find(
            (day: any) => day.day === today
        );
        return todayTimings;
    };

    const formatTime = (timeString: string) => {
        const time = new Date(timeString);
        return time.toLocaleTimeString("en-US", {
            hour: "2-digit",
            minute: "2-digit",
            hour12: true,
        });
    };

    if (loading) {
        return (
            <div className="min-h-screen bg-gray-50 flex items-center justify-center">
                <p className="text-gray-500">Loading Vendor/Stores details...</p>
            </div>
        );
    }

    if (!restaurant) {
        return (
            <div className="min-h-screen bg-gray-50 flex items-center justify-center">
                <p className="text-gray-500">Vendor/Store not found.</p>
            </div>
        );
    }

    const allImages =
        restaurant?.uploadRestaurantPhotos?.length
            ? restaurant.uploadRestaurantPhotos
            : [restaurant?.image].filter(Boolean);

    const mainImage = allImages[selectedImageIndex] || restaurant?.image;

    const allMenuImages = restaurant?.uploadRestaurantMenu || [];



    return (
        <div className="min-h-screen bg-gray-50">
            <div className="max-w-7xl mx-auto px-4 py-6">
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    {/* Left Column - Images */}
                    <div className="lg:col-span-2">
                        {/* Main Image */}
                        <div className="relative mb-4 cursor-pointer" onClick={() => {
                            setPreviewImages(allImages);
                            setPreviewInitialIndex(selectedImageIndex);
                            setIsPreviewOpen(true);
                        }}>
                            <img
                                src={getValidImage(mainImage)}
                                alt={restaurant?.restaurant_name}
                                className="w-full h-80 object-cover rounded-2xl"
                                onError={(e) => {
                                    const target = e.target as HTMLImageElement;
                                    target.src = "/placeholder-restaurant.jpg";
                                }}
                            />
                        </div>

                        {/* Thumbnail Images */}
                        {allImages.length > 1 && (
                            <div className="grid grid-cols-4 gap-3">
                                {allImages.slice(0, 4).map((imgUrl: string, index: number) => (
                                    <div key={index} className="relative cursor-pointer group"
                                        onClick={() => {
                                            if (index === 3 && allImages.length > 4) {
                                                setPreviewImages(allImages);
                                                setPreviewInitialIndex(4);
                                                setIsPreviewOpen(true);
                                            } else {
                                                setSelectedImageIndex(index);
                                            }
                                        }}
                                    >
                                        <img
                                            src={getValidImage(imgUrl)}
                                            // alt={`${restaurant?.restaurant_name} ${index + 1}`}
                                            className={`w-full h-20 object-cover rounded-lg transition-all ${selectedImageIndex === index
                                                ? "ring-2 ring-primary opacity-100"
                                                : "opacity-70 group-hover:opacity-100"
                                                }`}
                                        />
                                        {/* Show count on last image if more images exist */}
                                        {index === 3 && allImages.length > 4 && (
                                            <div className="absolute inset-0 bg-black bg-opacity-50 rounded-lg flex items-center justify-center group-hover:bg-opacity-40 transition-all">
                                                <span className="text-white font-semibold text-sm">
                                                    +{allImages.length - 4}
                                                </span>
                                            </div>
                                        )}
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>

                    {/* Right Column - Restaurant Info */}
                    <div className="bg-white rounded-2xl p-6 h-fit shadow-sm">
                        {/* Restaurant Name & Rating */}
                        <div className="mb-4">
                            <h1 className="text-2xl font-bold text-gray-900 mb-2">
                                {restaurant?.restaurant_name}
                            </h1>
                            <div className="flex items-center gap-2 mb-2">
                                {restaurant?.rating > 0 && (
                                    <div className="flex items-center gap-1 bg-yellow-500 text-white px-2 py-1 rounded text-sm font-semibold">
                                        <span>{restaurant?.rating > 0 ? restaurant?.rating : 0}</span>
                                        <Star size={12} fill="white" />
                                    </div>
                                )}
                                <span className="text-sm text-gray-600">

                                    {restaurant?.estimated_price_per_plate && (
                                        <>
                                            {" | "}
                                            <span>
                                                {currency}{(restaurant?.estimated_price_per_plate * 2).toFixed(2)} for two
                                            </span>
                                        </>
                                    )}
                                </span>

                            </div>
                        </div>

                        {/* Cuisine & Services */}
                        <div className="mb-4">
                            <div className="flex flex-wrap gap-1 mb-3">
                                {restaurant?.services?.slice(0, 3)?.map((service: any, index: number) => (
                                    <span
                                        key={service._id}
                                        className="text-gray-700 font-medium text-sm"
                                    >
                                        {service.name}
                                        {index < Math.min(restaurant.services.length - 1, 2) && ", "}
                                    </span>
                                ))}
                            </div>
                        </div>

                        {/* Location */}
                        <div className="mb-4">
                            <div className="flex items-start gap-2 text-sm text-gray-600 mb-1">
                                <MapPin size={16} className="text-gray-400 mt-0.5 flex-shrink-0" />
                                <div>
                                    <div>
                                        {restaurant?.address?.name}, {restaurant?.address?.city}
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Open Status & Estimated Price */}
                        <div className="mb-4">
                            <div className="flex items-center justify-between">
                                {(() => {
                                    const { isOpen, closeAt, nextOpen } = getTodayStatus(restaurant?.dine_out_working_day);

                                    return (
                                        <button
                                            onClick={() => setIsTimingsModalOpen(true)}
                                            className={`text-sm font-medium flex items-center ${isOpen ? "text-green-600" : "text-red-600"}`}
                                        >
                                            <Clock size={14} className="mr-1" />
                                            {isOpen ? (
                                                <>
                                                    Open now
                                                    {closeAt && <span> • Closes at {formatTime(closeAt.toString())}</span>}
                                                </>
                                            ) : (
                                                <>
                                                    Closed
                                                    {nextOpen && <span> • Opens at {formatTime(nextOpen.toString())}</span>}
                                                </>
                                            )}
                                        </button>
                                    );
                                })()}


                            </div>
                        </div>

                        {/* Facilities */}
                        <div className="mb-6">
                            <h3 className="font-semibold text-gray-900 mb-3">Amenities</h3>
                            <div className="space-y-2">
                                {Array.from({ length: Math.ceil(restaurant?.amenities?.length / 2) }).map(
                                    (_, rowIndex) => {
                                        const leftIndex = rowIndex * 2;
                                        const rightIndex = leftIndex + 1;

                                        const leftAmenity = restaurant?.amenities?.[leftIndex];
                                        const rightAmenity = restaurant?.amenities?.[rightIndex];

                                        return (
                                            <div key={rowIndex} className="flex justify-between text-gray-600">
                                                <div className="flex items-center gap-2 text-p1">
                                                    <div className="w-1.5 h-1.5 bg-gray-400 rounded-full"></div>
                                                    <span>{leftAmenity?.name}</span>
                                                </div>

                                                {rightAmenity ? (
                                                    <div className="flex items-center gap-2">
                                                        <div className="w-1.5 h-1.5 bg-gray-400 rounded-full"></div>
                                                        <span>{rightAmenity?.name}</span>
                                                    </div>
                                                ) : (
                                                    <div />
                                                )}
                                            </div>
                                        );
                                    }
                                )}
                            </div>
                        </div>
                        <button
                            onClick={() => router.push(`/dineout/${restaurantId}/slots`)}
                            className={`w-full text-white font-semibold py-3 px-4 rounded-lg transition-colors mb-4 
    ${(!todayStatus.isOpen || !userInfo) ? "opacity-60 cursor-not-allowed" : ""}`} style={{ backgroundColor: 'hsl(var(--primary))' }}
                            disabled={!todayStatus.isOpen || !userInfo}
                        >
                            Book a Table
                        </button>
                    </div>
                </div>

                {/* Food Menu Section */}
                <div className="mt-8 bg-white rounded-2xl p-6 shadow-sm">
                    <h2 className="text-2xl font-bold text-gray-900 mb-6">Food Menu</h2>
                    {allMenuImages.length > 0 ? (
                        <div className="relative">
                            <Swiper
                                slidesPerView={1.2}
                                spaceBetween={16}
                                pagination={{
                                    clickable: true,
                                }}
                                breakpoints={{
                                    640: {
                                        slidesPerView: 2.2,
                                    },
                                    1024: {
                                        slidesPerView: 3.2,
                                    },
                                }}
                                modules={[Pagination]}
                                className="nearby-swiper"
                            >
                                {allMenuImages.map((menuUrl: string, index: number) => (
                                    <SwiperSlide key={index}>
                                        <div className="bg-gray-50 rounded-lg overflow-hidden h-48 flex items-center justify-center cursor-pointer hover:opacity-90 transition-opacity"
                                            onClick={() => {
                                                setPreviewImages(allMenuImages);
                                                setPreviewInitialIndex(index);
                                                setIsPreviewOpen(true);
                                            }}
                                        >
                                            <img
                                                src={getValidImage(menuUrl)}
                                                alt={`Menu ${index + 1}`}
                                                className="w-full h-full object-cover"
                                            />
                                        </div>
                                    </SwiperSlide>
                                ))}
                            </Swiper>
                        </div>
                    ) : restaurant?.category && restaurant.category.length > 0 ? (
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {restaurant.category.map((cat: any) => (
                                <div
                                    key={cat._id}
                                    className="border border-gray-200 rounded-lg p-4 hover:bg-gray-50 cursor-pointer"
                                    onClick={() => {
                                        setPreviewImages([cat.category_image]);
                                        setPreviewInitialIndex(0);
                                        setIsPreviewOpen(true);
                                    }}
                                >
                                    <h3 className="font-semibold text-gray-900 mb-2">
                                        {cat.category_name}
                                    </h3>
                                    {cat.category_image && (
                                        <img
                                            src={getValidImage(cat.category_image)}
                                            alt={cat.category_name}
                                            className="w-full h-32 object-cover rounded-lg"
                                            onError={(e) => {
                                                const target = e.target as HTMLImageElement;
                                                target.src = "/placeholder-category.jpg";
                                            }}
                                        />
                                    )}
                                </div>
                            ))}
                        </div>
                    ) : (
                        <p className="text-gray-600">Menu information will be displayed here...</p>
                    )}
                </div>

                {/* Location & Timings Section */}
                <div className="mt-8 space-y-8 mx-auto">
                    {/* Location */}
                    <div className="bg-white rounded-2xl p-6 shadow-sm">
                        <h2 className="text-h2 font-bold text-gray-900 mb-4">Location</h2>
                        <div className="flex items-start gap-3">
                            <MapPin size={20} className="text-gray-700 mt-1 flex-shrink-0" />
                            <div>
                                <p className="text-gray-800 text-p1">
                                    {restaurant?.address?.name},{" "}
                                    {restaurant?.address?.area ? restaurant.address.area + ", " : ""}
                                    {restaurant?.address?.city}
                                    {restaurant?.address?.pincode
                                        ? ` - ${restaurant.address.pincode}`
                                        : ""}
                                </p>
                                <a
                                    href={`https://maps.google.com/?q=${restaurant?.address?.lat},${restaurant?.address?.long}`}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="text-primary font-semibold text-p1 mt-1 inline-block hover:underline"
                                >
                                    View on Maps
                                </a>
                            </div>
                        </div>
                    </div>

                    {/* Timings */}
                    <div className="bg-white rounded-2xl p-6 shadow-sm">
                        <h2 className="text-h2 font-bold text-gray-900 mb-4">Timings</h2>
                        <div className="flex items-start gap-3">
                            <Clock size={20} className="text-gray-600 mt-1 flex-shrink-0" />
                            <div className="text-p1">
                                {(() => {
                                    const { isOpen, closeAt, nextOpen } = getTodayStatus(restaurant?.dine_out_working_day);

                                    return (
                                        <p className="text-gray-800 font-medium">
                                            {isOpen
                                                ? `Open till ${closeAt ? formatTime(closeAt.toString()) : ""}`
                                                : `Closed${nextOpen ? ` • Opens at ${formatTime(nextOpen.toString())}` : ""}`}
                                        </p>
                                    );
                                })()}

                                <button
                                    onClick={() => setIsTimingsModalOpen(true)}
                                    className="text-primary font-semibold text-p1 mt-1 hover:underline"
                                >
                                    See all timings
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <TimingsModal
                    isOpen={isTimingsModalOpen}
                    onClose={() => setIsTimingsModalOpen(false)}
                    workingDays={restaurant?.dine_out_working_day}
                />

                <ImagePreviewModal
                    isOpen={isPreviewOpen}
                    onClose={() => setIsPreviewOpen(false)}
                    images={previewImages}
                    initialIndex={previewInitialIndex}
                />
            </div>
        </div>
    );
};

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