import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Calendar, Clock, Users, MapPin, ChevronRight, Utensils, AlertCircle, Trash2 } from 'lucide-react';
import { Link, useNavigate } from 'react-router-dom';

const MyBookings = () => {
  const [bookings, setBookings] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const navigate = useNavigate();
  const userInfo = JSON.parse(localStorage.getItem('userInfo'));

  useEffect(() => {
    if (!userInfo) {
      navigate('/login');
      return;
    }

    const fetchBookings = async () => {
      try {
        const config = {
          headers: { Authorization: `Bearer ${userInfo.token}` },
        };
        const { data } = await axios.get('http://localhost:5000/api/bookings/my', config);
        setBookings(data);
      } catch (err) {
        setError('Failed to load your bookings');
      } finally {
        setLoading(false);
      }
    };

    fetchBookings();
  }, [userInfo, navigate]);

  const handleCancelBooking = async (id) => {
      if (!window.confirm('Are you sure you want to cancel this reservation?')) return;
      try {
          const config = { headers: { Authorization: `Bearer ${userInfo.token}` } };
          await axios.delete(`http://localhost:5000/api/bookings/${id}`, config);
          setBookings(bookings.filter(b => b._id !== id));
          alert('Booking cancelled successfully');
      } catch (err) {
          alert('Failed to cancel booking');
      }
  };

  if (loading) return <div className="pt-32 text-center text-gray-400 font-bold h-screen bg-gray-50 flex items-center justify-center">Loading your reservations...</div>;

  return (
    <div className="min-h-screen bg-[#f8f9fa] pt-32 pb-20">
      <div className="container mx-auto px-6 max-w-5xl">
        <header className="mb-12">
            <h1 className="text-4xl md:text-5xl font-bold text-secondary font-outfit mb-4">My Reservations</h1>
            <p className="text-gray-400 text-lg font-medium">Keep track of your upcoming dining experiences.</p>
        </header>

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

        <div className="space-y-8">
          {bookings.length > 0 ? (
            bookings.map((booking) => (
              <div key={booking._id} className="bg-white rounded-[40px] p-8 shadow-sm border border-gray-100 group hover:shadow-xl transition-all relative overflow-hidden">
                {/* Status Badge */}
                <div className="absolute top-8 right-8">
                    <span className={`px-4 py-1.5 rounded-full text-[10px] font-bold tracking-widest uppercase ${
                        booking.status === 'confirmed' ? 'bg-green-100 text-green-600' : 
                        booking.status === 'cancelled' ? 'bg-red-100 text-red-600' : 'bg-primary/10 text-primary'
                    }`}>
                        {booking.status}
                    </span>
                </div>

                <div className="flex flex-col md:flex-row gap-10 items-start md:items-center">
                    {/* Restaurant Info */}
                    <div className="flex gap-6 items-center flex-1">
                        <div className="w-24 h-24 bg-gray-50 rounded-[32px] overflow-hidden shadow-inner flex items-center justify-center border border-gray-50 group-hover:border-primary/20 transition-colors">
                            {booking.restaurant?.image ? (
                                <img 
                                    src={`http://localhost:5000/${booking.restaurant.image}`} 
                                    className="w-full h-full object-cover"
                                    alt={booking.restaurant.name}
                                />
                            ) : (
                                <Utensils size={32} className="text-gray-200" />
                            )}
                        </div>
                        <div>
                            <h3 className="text-2xl font-bold text-secondary mb-2 group-hover:text-primary transition-colors">
                                {booking.restaurant?.name}
                            </h3>
                            <p className="flex items-center gap-2 text-gray-400 text-sm font-medium">
                                <MapPin size={14} className="text-primary" />
                                {booking.restaurant?.location}
                            </p>
                        </div>
                    </div>

                    {/* Booking Stats */}
                    <div className="flex flex-wrap gap-8 md:gap-12 border-t md:border-t-0 md:border-l border-gray-50 pt-8 md:pt-0 md:pl-12">
                        <div className="space-y-1">
                            <span className="text-[10px] font-bold text-gray-300 uppercase tracking-widest block">Date</span>
                            <div className="flex items-center gap-2 font-bold text-secondary">
                                <Calendar size={16} className="text-primary" />
                                {booking.bookingDate}
                            </div>
                        </div>
                        <div className="space-y-1">
                            <span className="text-[10px] font-bold text-gray-300 uppercase tracking-widest block">Time</span>
                            <div className="flex items-center gap-2 font-bold text-secondary">
                                <Clock size={16} className="text-primary" />
                                {booking.bookingTime}
                            </div>
                        </div>
                        <div className="space-y-1">
                            <span className="text-[10px] font-bold text-gray-300 uppercase tracking-widest block">Guests</span>
                            <div className="flex items-center gap-2 font-bold text-secondary">
                                <Users size={16} className="text-primary" />
                                {booking.guests} People
                            </div>
                        </div>
                    </div>

                    {/* Actions */}
                    <div className="flex gap-4 w-full md:w-auto">
                        <Link 
                            to={`/restaurant/${booking.restaurant?._id}`}
                            className="bg-gray-50 text-gray-500 p-4 rounded-2xl hover:bg-gray-100 transition-all shadow-sm"
                        >
                            <ChevronRight size={20} />
                        </Link>
                        {booking.status === 'pending' && (
                            <button 
                                onClick={() => handleCancelBooking(booking._id)}
                                className="bg-red-50 text-red-500 p-4 rounded-2xl hover:bg-red-500 hover:text-white transition-all shadow-sm"
                            >
                                <Trash2 size={20} />
                            </button>
                        )}
                    </div>
                </div>
              </div>
            ))
          ) : (
            <div className="text-center py-24 bg-white rounded-[48px] shadow-sm border border-gray-100 border-dashed">
                <div className="w-20 h-20 bg-gray-50 rounded-3xl flex items-center justify-center mx-auto mb-6">
                    <Calendar size={32} className="text-gray-200" />
                </div>
                <h3 className="text-2xl font-bold text-secondary mb-2">No Bookings Found</h3>
                <p className="text-gray-400 mb-8 max-w-xs mx-auto">You haven't made any restaurant reservations yet.</p>
                <Link to="/" className="inline-flex items-center gap-2 bg-secondary text-white px-8 py-4 rounded-2xl font-bold shadow-xl hover:bg-black transition-all">
                    Explore Restaurants <ChevronRight size={18} />
                </Link>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default MyBookings;
