import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import {
  MapPin,
  Clock,
  Star,
  Info,
  Menu,
  ChevronRight,
  Calendar,
  Users,
  AlertCircle,
  Utensils,
} from "lucide-react";
import axios from "axios";

const RestaurantDetails = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));

  const [restaurant, setRestaurant] = useState(null);
  const [loading, setLoading] = useState(true);
  const [selectedDate, setSelectedDate] = useState("");
  const [selectedTime, setSelectedTime] = useState("");
  const [guests, setGuests] = useState(2);
  const [error, setError] = useState("");

  useEffect(() => {
    const fetchRestaurant = async () => {
      try {
        const { data } = await axios.get(
          `http://localhost:5000/api/restaurants/${id}`,
        );
        setRestaurant(data);
      } catch (err) {
        console.error("Failed to fetch restaurant details", err);
      } finally {
        setLoading(false);
      }
    };
    fetchRestaurant();
  }, [id]);

  const handleBooking = async (e) => {
    e.preventDefault();
    setError("");

    if (!userInfo) {
      navigate("/login");
      return;
    }

    try {
      const config = {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${userInfo.token}`,
        },
      };

      await axios.post(
        "http://localhost:5000/api/bookings",
        {
          restaurantId: id,
          guests,
          bookingDate: selectedDate,
          bookingTime: selectedTime,
        },
        config,
      );

      alert("Booking Successfully Created!");
      navigate("/bookings");
    } catch (err) {
      setError(err.response?.data?.message || "Booking failed");
    }
  };

  if (loading)
    return (
      <div className="pt-32 text-center text-gray-500 font-bold h-screen">
        Loading exquisite details...
      </div>
    );
  if (!restaurant)
    return (
      <div className="pt-32 text-center text-red-500 font-bold h-screen">
        Restaurant not found.
      </div>
    );

  return (
    <div className="pt-20 bg-[#fcfbf7] min-h-screen">
      {/* Header Image */}
      <div className="relative h-[500px] w-full">
        <img
          src={
            restaurant.image
              ? restaurant.image.startsWith("http")
                ? restaurant.image
                : `http://localhost:5000/${restaurant.image}`
              : "https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?auto=format&fit=crop&q=80&w=1200"
          }
          alt={restaurant.name}
          className="w-full h-full object-cover"
        />
        <div className="absolute inset-0 bg-gradient-to-t from-black via-black/20 to-transparent"></div>
        <div className="absolute bottom-16 left-0 right-0">
          <div className="container mx-auto px-6 text-white text-center md:text-left">
            <div className="flex flex-wrap items-center justify-center md:justify-start gap-4 mb-6">
              <span className="bg-primary px-6 py-2 rounded-2xl text-xs font-bold uppercase tracking-widest shadow-xl shadow-primary/20">
                {restaurant.cuisine || "Modern Fusion"}
              </span>
              <div className="flex items-center gap-2 bg-white/10 backdrop-blur-md px-4 py-2 rounded-2xl border border-white/10">
                <Star className="text-orange-400 fill-orange-400" size={16} />
                <span className="text-sm font-bold">4.8 Rating</span>
              </div>
            </div>
            <h1 className="text-5xl md:text-7xl font-bold font-outfit mb-4">
              {restaurant.name}
            </h1>
            <p className="flex items-center justify-center md:justify-start gap-3 text-gray-300 text-lg">
              <MapPin size={22} className="text-primary" />
              {restaurant.location}
            </p>
          </div>
        </div>
      </div>

      <div className="container mx-auto px-6 py-20">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-16">
          {/* Main Info */}
          <div className="lg:col-span-7 space-y-20">
            <section>
              <h2 className="text-3xl font-bold mb-8 flex items-center gap-4 text-secondary font-outfit">
                <div className="w-10 h-10 bg-primary/10 rounded-xl flex items-center justify-center text-primary">
                  <Info size={24} />
                </div>
                About the Restaurant
              </h2>
              <p className="text-gray-500 text-xl leading-relaxed font-medium">
                {restaurant.description ||
                  "Enter a world of culinary excellence where every dish is a masterpiece."}
              </p>
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-6 mt-12">
                <div className="bg-white p-6 rounded-[32px] shadow-sm border border-gray-100 group hover:border-primary transition-all">
                  <span className="text-gray-400 text-xs font-bold uppercase block mb-2 tracking-widest">
                    Cuisine
                  </span>
                  <span className="font-bold text-secondary text-lg">
                    {restaurant.cuisine || "International"}
                  </span>
                </div>
                <div className="bg-white p-6 rounded-[32px] shadow-sm border border-gray-100 group hover:border-primary transition-all">
                  <span className="text-gray-400 text-xs font-bold uppercase block mb-2 tracking-widest">
                    Price Level
                  </span>
                  <span className="font-bold text-primary text-lg">
                    {restaurant.priceRange || "$$$"}
                  </span>
                </div>
                <div className="bg-white p-6 rounded-[32px] shadow-sm border border-gray-100 group hover:border-primary transition-all">
                  <span className="text-gray-400 text-xs font-bold uppercase block mb-2 tracking-widest">
                    Business Hours
                  </span>
                  <span className="font-bold text-secondary text-lg">
                    {restaurant.openingTime} - {restaurant.closingTime}
                  </span>
                </div>
              </div>
            </section>

            <section>
              <div className="flex justify-between items-center mb-10">
                <h2 className="text-3xl font-bold flex items-center gap-4 text-secondary font-outfit">
                  <div className="w-10 h-10 bg-primary/10 rounded-xl flex items-center justify-center text-primary">
                    <Menu size={24} />
                  </div>
                  Signature Menu
                </h2>
                <button className="text-primary font-bold hover:underline">
                  View All Dishes
                </button>
              </div>
              <div className="space-y-6">
                {restaurant.menu && restaurant.menu.length > 0 ? (
                  restaurant.menu.map((item, index) => (
                    <div
                      key={index}
                      className="bg-white p-8 rounded-[32px] shadow-sm border border-gray-100 flex justify-between items-center group hover:shadow-xl hover:translate-x-2 transition-all cursor-pointer"
                    >
                      <div className="flex gap-6 items-center">
                        <div className="w-20 h-20 bg-gray-50 rounded-2xl overflow-hidden shadow-inner flex items-center justify-center">
                          <Utensils className="text-gray-200" size={30} />
                        </div>
                        <div>
                          <h4 className="font-bold text-xl text-secondary mb-1">
                            {item.name}
                          </h4>
                          <p className="text-gray-400 text-sm">
                            {item.category}
                          </p>
                        </div>
                      </div>
                      <span className="text-2xl font-bold text-primary">
                        ${item.price}
                      </span>
                    </div>
                  ))
                ) : (
                  <div className="p-10 text-center bg-white rounded-3xl border border-dashed border-gray-200 text-gray-400">
                    Menu not updated yet.
                  </div>
                )}
              </div>
            </section>
          </div>

          {/* Booking Sidebar */}
          <div className="lg:col-span-5 relative">
            <div className="sticky top-32 bg-white rounded-[48px] p-10 shadow-2xl border border-gray-50">
              <div className="mb-8">
                <h3 className="text-3xl font-bold text-secondary mb-2 font-outfit">
                  Reserve a Table
                </h3>
                <p className="text-gray-400 font-medium">
                  Guaranteed seating for your special event.
                </p>
              </div>

              {error && (
                <div className="bg-red-50 text-red-500 p-4 rounded-2xl mb-8 flex items-center gap-3 text-sm font-bold">
                  <AlertCircle size={20} />
                  {error}
                </div>
              )}

              <form onSubmit={handleBooking} className="space-y-8">
                <div className="grid grid-cols-2 gap-6">
                  <div className="space-y-2">
                    <label className="text-xs font-bold text-gray-400 uppercase tracking-widest ml-1">
                      Date
                    </label>
                    <div className="relative">
                      <Calendar
                        className="absolute left-4 top-4 text-primary"
                        size={20}
                      />
                      <input
                        type="date"
                        className="w-full bg-gray-50 border border-gray-100 rounded-2xl py-4 pl-12 pr-4 outline-none focus:border-primary transition-all font-bold text-secondary text-sm"
                        value={selectedDate}
                        onChange={(e) => setSelectedDate(e.target.value)}
                        required
                      />
                    </div>
                  </div>
                  <div className="space-y-2">
                    <label className="text-xs font-bold text-gray-400 uppercase tracking-widest ml-1">
                      Time
                    </label>
                    <div className="relative">
                      <Clock
                        className="absolute left-4 top-4 text-primary"
                        size={20}
                      />
                      <select
                        className="w-full bg-gray-50 border border-gray-100 rounded-2xl py-4 pl-12 pr-4 outline-none focus:border-primary transition-all font-bold text-secondary text-sm appearance-none"
                        value={selectedTime}
                        onChange={(e) => setSelectedTime(e.target.value)}
                        required
                      >
                        <option value="">Time</option>
                        <option value="18:00">06:00 PM</option>
                        <option value="19:00">07:00 PM</option>
                        <option value="20:00">08:00 PM</option>
                        <option value="21:00">09:00 PM</option>
                      </select>
                    </div>
                  </div>
                </div>

                <div className="space-y-2">
                  <label className="text-xs font-bold text-gray-400 uppercase tracking-widest ml-1">
                    Number of Guests
                  </label>
                  <div className="relative">
                    <Users
                      className="absolute left-6 top-4 text-primary"
                      size={20}
                    />
                    <div className="flex items-center gap-4 bg-gray-50 border border-gray-100 rounded-2xl py-2 px-6 pl-14">
                      <button
                        type="button"
                        onClick={() => setGuests(Math.max(1, guests - 1))}
                        className="w-10 h-10 rounded-full bg-white shadow-sm flex items-center justify-center font-bold text-lg hover:bg-gray-100"
                      >
                        -
                      </button>
                      <span className="flex-1 text-center font-bold text-xl">
                        {guests}
                      </span>
                      <button
                        type="button"
                        onClick={() => setGuests(guests + 1)}
                        className="w-10 h-10 rounded-full bg-white shadow-sm flex items-center justify-center font-bold text-lg hover:bg-gray-100"
                      >
                        +
                      </button>
                    </div>
                  </div>
                </div>

                <div className="bg-primary/5 p-6 rounded-3xl border border-primary/10">
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-gray-500 font-medium">
                      Standard Reserveration
                    </span>
                    <span className="font-bold text-primary">Free</span>
                  </div>
                  <p className="text-[10px] text-gray-400 font-medium leading-relaxed">
                    *By clicking Confirm, you agree to our terms of service and
                    the restaurant's cancellation policy.
                  </p>
                </div>

                <button
                  type="submit"
                  className="w-full bg-secondary text-white py-5 rounded-[24px] font-bold shadow-2xl hover:bg-black transition-all hover:scale-[1.02] active:scale-95 flex items-center justify-center gap-3 text-lg"
                >
                  Confirm Table Booking
                  <ChevronRight size={22} className="text-primary" />
                </button>

                {!userInfo && (
                  <p className="text-center text-sm text-gray-400 font-medium">
                    Login is required to complete booking.
                  </p>
                )}
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default RestaurantDetails;
