import React, { useState, useEffect } from 'react';
import { 
  useParams, 
  useNavigate, 
  Link 
} from 'react-router-dom';
import { useForm, Controller } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import { 
  Calendar,
  Users,
  CreditCard,
  FileText,
  ArrowLeft,
  AlertCircle,
  Loader2,
  CheckCircle,
  Shield,
  Sparkles,
  MapPin,
  Plus,
  Minus,
  X,
} from 'lucide-react';
import { toast } from 'react-toastify';
import { getRoomById, getRoomBookedDates, type Room } from 
  '../../services/api/roomService';
import { 
  createBooking,
  checkRoomAvailability,
  type BookingData,
} from '../../services/api/bookingService';
import { serviceService, Service, promotionService, Promotion } from '../../services/api';
import { createPayPalOrder } from '../../services/api/paymentService';
import useAuthStore from '../../store/useAuthStore';
import { useAuthModal } from '../../contexts/AuthModalContext';
import { 
  bookingValidationSchema, 
  type BookingFormData 
} from '../../validators/bookingValidator';
import Loading from '../../components/common/Loading';
import { useFormatCurrency } from '../../hooks/useFormatCurrency';
import { formatDateLocal } from '../../utils/format';
import Recaptcha from '../../components/common/Recaptcha';
import { recaptchaService } from '../../services/api/systemSettingsService';

const BookingPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { isAuthenticated, userInfo } = useAuthStore();
  const { openModal } = useAuthModal();
  const { formatCurrency, currency } = useFormatCurrency();

  const [room, setRoom] = useState<Room | null>(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [recaptchaToken, setRecaptchaToken] = useState<string | null>(null);
  const [services, setServices] = useState<Service[]>([]);
  const [selectedServices, setSelectedServices] = useState<Array<{ service: Service; quantity: number }>>([]);
  const [bookedDates, setBookedDates] = useState<Date[]>([]);
  const [promotionCode, setPromotionCode] = useState('');
  const [selectedPromotion, setSelectedPromotion] = useState<Promotion | null>(null);
  const [promotionDiscount, setPromotionDiscount] = useState(0);
  const [validatingPromotion, setValidatingPromotion] = useState(false);
  const [promotionError, setPromotionError] = useState<string | null>(null);

  
  useEffect(() => {
    if (!isAuthenticated) {
      toast.error(
        'Please login to make a booking'
      );
      openModal('login');
    } else if (userInfo?.role === 'admin' || userInfo?.role === 'staff' || userInfo?.role === 'accountant') {
      toast.error('Admin, staff, and accountant users cannot make bookings');
      if (userInfo?.role === 'admin') {
        navigate('/admin/dashboard', { replace: true });
      } else if (userInfo?.role === 'staff') {
        navigate('/staff/dashboard', { replace: true });
      } else if (userInfo?.role === 'accountant') {
        navigate('/accountant/dashboard', { replace: true });
      }
    }
  }, [isAuthenticated, userInfo, navigate, id]);

  
  useEffect(() => {
    if (id && isAuthenticated) {
      fetchRoomDetails(Number(id));
      fetchServices();
      fetchBookedDates(Number(id));
    }
  }, [id, isAuthenticated]);

  const fetchBookedDates = async (roomId: number) => {
    try {
      const response = await getRoomBookedDates(roomId);
      
      const isSuccess = response.success === true || (response as any).status === 'success';
      
      if (isSuccess && response.data?.booked_dates) {
        
        const dates = response.data.booked_dates.map((dateStr: string) => {
          const [year, month, day] = dateStr.split('-').map(Number);
          const date = new Date(year, month - 1, day);
          
          date.setHours(0, 0, 0, 0);
          date.setMinutes(0, 0, 0);
          return date;
        });
        setBookedDates(dates);
      }
    } catch (err) {
      console.error('Error fetching booked dates:', err);
      
    }
  };

  
  const isDateBooked = (date: Date): boolean => {
    if (!date || bookedDates.length === 0) return false;
    const normalizedDate = new Date(date);
    normalizedDate.setHours(0, 0, 0, 0);
    return bookedDates.some(bookedDate => {
      const normalizedBooked = new Date(bookedDate);
      normalizedBooked.setHours(0, 0, 0, 0);
      return normalizedDate.getTime() === normalizedBooked.getTime();
    });
  };

  
  const doesRangeIncludeBookedDates = (startDate: Date, endDate: Date): boolean => {
    if (!startDate || !endDate || bookedDates.length === 0) return false;
    const start = new Date(startDate);
    start.setHours(0, 0, 0, 0);
    const end = new Date(endDate);
    end.setHours(0, 0, 0, 0);
    
    let currentDate = new Date(start);
    while (currentDate < end) {
      if (isDateBooked(currentDate)) {
        return true;
      }
      currentDate.setDate(currentDate.getDate() + 1);
    }
    return false;
  };

  const fetchServices = async () => {
    try {
      const response = await serviceService.getServices({
        status: 'active',
        limit: 100,
      });
      setServices(response.data.services || []);
    } catch (err: any) {
      console.error('Error fetching services:', err);
      
    }
  };

  const fetchRoomDetails = async (roomId: number) => {
    try {
      setLoading(true);
      setError(null);
      const response = await getRoomById(roomId);

      if (
        (response.success || 
          (response as any).status === 'success') && 
        response.data?.room
      ) {
        setRoom(response.data.room);
      } else {
        throw new Error('Unable to load room information');
      }
    } catch (err: any) {
      console.error('Error fetching room:', err);
      const message =
        err.response?.data?.message ||
        'Unable to load room information';
      setError(message);
      toast.error(message);
    } finally {
      setLoading(false);
    }
  };

  
  const {
    control,
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm<BookingFormData & { invoiceInfo?: any }>({
    resolver: yupResolver(bookingValidationSchema),
    defaultValues: {
      checkInDate: undefined,
      checkOutDate: undefined,
      guestCount: 1,
      notes: '',
      paymentMethod: 'cash',
      fullName: userInfo?.name || '',
      email: userInfo?.email || '',
      phone: userInfo?.phone || '',
      invoiceInfo: {
        company_name: '',
        company_address: '',
        company_tax_id: '',
        customer_tax_id: '',
      },
    },
  });

  
  const checkInDate = watch('checkInDate');
  const checkOutDate = watch('checkOutDate');
  const paymentMethod = watch('paymentMethod');

  
  const numberOfNights =
    checkInDate && checkOutDate
      ? Math.ceil(
          (checkOutDate.getTime() - 
            checkInDate.getTime()) /
            (1000 * 60 * 60 * 24)
        )
      : 0;

  
  const roomPrice = 
    (room?.price && room.price > 0) 
      ? room.price 
      : (room?.room_type?.base_price || 0);
  const roomTotal = numberOfNights * roomPrice;
  
  
  const servicesTotal = selectedServices.reduce((sum, item) => {
    return sum + (item.service.price * item.quantity);
  }, 0);
  
  const subtotal = roomTotal + servicesTotal;
  const totalPrice = Math.max(0, subtotal - promotionDiscount);

  
  const formatPrice = (price: number) => formatCurrency(price);

  
  const handleValidatePromotion = async () => {
    if (!promotionCode.trim()) {
      setPromotionError('Please enter a promotion code');
      return;
    }

    if (subtotal === 0) {
      setPromotionError('Please select dates first');
      return;
    }

    try {
      setValidatingPromotion(true);
      setPromotionError(null);
      
      const response = await promotionService.validatePromotion(
        promotionCode.toUpperCase().trim(),
        subtotal
      );

      if (response.success && response.data) {
        setSelectedPromotion(response.data.promotion);
        setPromotionDiscount(response.data.discount);
        toast.success(`Promotion "${response.data.promotion.name}" applied!`);
      } else {
        throw new Error(response.message || 'Invalid promotion code');
      }
    } catch (error: any) {
      setPromotionError(error.response?.data?.message || error.message || 'Invalid promotion code');
      setSelectedPromotion(null);
      setPromotionDiscount(0);
      toast.error(error.response?.data?.message || error.message || 'Invalid promotion code');
    } finally {
      setValidatingPromotion(false);
    }
  };

  
  const handleRemovePromotion = () => {
    setPromotionCode('');
    setSelectedPromotion(null);
    setPromotionDiscount(0);
    setPromotionError(null);
    toast.info('Promotion removed');
  };

  
  const onSubmit = async (data: BookingFormData) => {
    if (!room) return;

    
    if (recaptchaToken) {
      try {
        const verifyResponse = await recaptchaService.verifyRecaptcha(recaptchaToken);
        if (verifyResponse.status === 'error' || !verifyResponse.data.verified) {
          toast.error('reCAPTCHA verification failed. Please try again.');
          setRecaptchaToken(null);
          return;
        }
      } catch (error) {
        toast.error('reCAPTCHA verification failed. Please try again.');
        setRecaptchaToken(null);
        return;
      }
    }

    try {
      setSubmitting(true);

      
      const checkInDateStr = formatDateLocal(data.checkInDate);
      const checkOutDateStr = formatDateLocal(data.checkOutDate);

      
      const checkIn = new Date(data.checkInDate);
      checkIn.setHours(0, 0, 0, 0);
      const checkOut = new Date(data.checkOutDate);
      checkOut.setHours(0, 0, 0, 0);

      
      if (isDateBooked(checkIn)) {
        toast.error('Check-in date is already booked. Please select another date.');
        return;
      }

      
      
      
      const selectedDates: Date[] = [];
      let currentDate = new Date(checkIn);
      while (currentDate < checkOut) {
        if (isDateBooked(currentDate)) {
          toast.error('The selected date range includes booked dates. Please select different dates.');
          return;
        }
        selectedDates.push(new Date(currentDate));
        currentDate.setDate(currentDate.getDate() + 1);
      }

      
      const availability = await checkRoomAvailability(
        room.id,
        checkInDateStr,
        checkOutDateStr
      );

      if (!availability.available) {
        toast.error(
          availability.message || 
          'Room is already booked during this time'
        );
        return;
      }

      
      const bookingData: BookingData & { invoice_info?: any } = {
        room_id: room.id,
        check_in_date: checkInDateStr,
        check_out_date: checkOutDateStr,
        guest_count: data.guestCount,
        notes: data.notes || '',
        payment_method: data.paymentMethod,
        total_price: totalPrice,
        guest_info: {
          full_name: data.fullName,
          email: data.email,
          phone: data.phone,
        },
        services: selectedServices.map(item => ({
          service_id: item.service.id,
          quantity: item.quantity,
        })),
        promotion_code: selectedPromotion?.code || undefined,
        invoice_info: (data as any).invoiceInfo ? {
          company_name: (data as any).invoiceInfo.company_name || undefined,
          company_address: (data as any).invoiceInfo.company_address || undefined,
          company_tax_id: (data as any).invoiceInfo.company_tax_id || undefined,
          customer_tax_id: (data as any).invoiceInfo.customer_tax_id || undefined,
        } : undefined,
      };

      
      const response = await createBooking(bookingData);

      if (
        response.success && 
        response.data?.booking
      ) {
        const bookingId = response.data.booking.id;
        
        
        if (paymentMethod === 'paypal') {
          try {
            
            const currentUrl = window.location.origin;
            const returnUrl = `${currentUrl}/payment/paypal/return?bookingId=${bookingId}`;
            const cancelUrl = `${currentUrl}/payment/paypal/cancel?bookingId=${bookingId}`;
            
            const paypalResponse = await createPayPalOrder(
              bookingId,
              totalPrice,
              currency || 'USD', 
              returnUrl,
              cancelUrl
            );

            if (paypalResponse.success && paypalResponse.data?.approval_url) {
              
              window.location.href = paypalResponse.data.approval_url;
              return; 
            } else {
              throw new Error(paypalResponse.message || 'Failed to initialize PayPal payment');
            }
          } catch (paypalError: any) {
            console.error('Error initializing PayPal payment:', paypalError);
            toast.error(
              paypalError.response?.data?.message || 
              paypalError.message || 
              'Failed to initialize PayPal payment. Please try again or contact support.'
            );
            
            navigate(`/booking-success/${bookingId}`);
            return;
          }
        }
        
        
        if (paymentMethod === 'cash') {
          toast.success(
            '📋 Booking created! Please pay the 20% deposit to confirm your booking.',
            { icon: <CheckCircle className="text-green-500" /> }
          );
          
          navigate(`/payment/deposit/${bookingId}`);
          return;
        }
        
        
        toast.success(
          '🎉 Booking successful!',
          { icon: <CheckCircle className="text-green-500" /> }
        );
        
        
        navigate(`/booking-success/${bookingId}`);
      } else {
        throw new Error(
          response.message || 
          'Unable to create booking'
        );
      }
    } catch (err: any) {
      console.error('Error creating booking:', err);
      
      
      if (err.response?.status === 409) {
        toast.error(
          '❌ Room is already booked during this time. ' +
          'Please select different dates.'
        );
      } else if (err.response?.status === 400) {
        toast.error(
          err.response?.data?.message || 
          'Invalid booking information'
        );
      } else {
        const message =
          err.response?.data?.message ||
          'Unable to book room. Please try again.';
        toast.error(message);
      }
      setRecaptchaToken(null);
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div 
        className="min-h-screen bg-gradient-to-b from-[#0f0f0f] via-[#1a1a1a] to-[#0f0f0f] py-8 w-screen relative -mt-6 -mb-6"
        style={{ 
          marginLeft: 'calc(50% - 50vw)',
          marginRight: 'calc(50% - 50vw)',
          width: '100vw',
          zIndex: 1
        }}
      >
        <div className="w-full px-2 sm:px-4 md:px-6 lg:px-8">
          <Loading fullScreen text="Loading room details..." />
        </div>
      </div>
    );
  }

  if (error || !room) {
    return (
      <div 
        className="min-h-screen bg-gradient-to-b from-[#0f0f0f] via-[#1a1a1a] to-[#0f0f0f] py-8 w-screen relative -mt-6 -mb-6"
        style={{ 
          marginLeft: 'calc(50% - 50vw)',
          marginRight: 'calc(50% - 50vw)',
          width: '100vw',
          zIndex: 1
        }}
      >
        <div className="w-full px-2 sm:px-4 md:px-6 lg:px-8 py-8">
          <div 
            className="bg-gradient-to-br from-red-900/20 to-red-800/10 
              border border-red-500/30 rounded-xl p-12 text-center 
              backdrop-blur-xl shadow-2xl shadow-red-500/10"
          >
            <AlertCircle 
              className="w-12 h-12 text-red-400 
                mx-auto mb-4" 
            />
            <p className="text-red-300 font-light text-lg mb-6 tracking-wide">
              {error || 'Room not found'}
            </p>
            <Link
              to="/rooms"
              className="inline-flex items-center gap-2 bg-gradient-to-r 
                from-[#d4af37] to-[#c9a227] text-[#0f0f0f] 
                px-6 py-3 rounded-sm hover:from-[#f5d76e] 
                hover:to-[#d4af37] transition-all duration-300 
                font-medium tracking-wide shadow-lg shadow-[#d4af37]/30"
            >
              <ArrowLeft className="w-5 h-5" />
              Back to Room List
            </Link>
          </div>
        </div>
      </div>
    );
  }

  const roomType = room.room_type;
  if (!roomType) return null;

  return (
    <div 
      className="min-h-screen bg-gradient-to-b from-[#0f0f0f] via-[#1a1a1a] to-[#0f0f0f] py-8 sm:py-12 w-screen relative -mt-6 -mb-6"
      style={{ 
        marginLeft: 'calc(50% - 50vw)',
        marginRight: 'calc(50% - 50vw)',
        width: '100vw',
        zIndex: 1
      }}
    >
      <div className="w-full px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4">
        {}
        <Link
          to={`/rooms/${room.room_number}`}
          className="inline-flex items-center gap-1 
            text-[#d4af37]/80 hover:text-[#d4af37] 
            mb-3 transition-all duration-300 
            group font-light tracking-wide text-xs sm:text-sm"
        >
          <ArrowLeft className="w-3.5 h-3.5 group-hover:-translate-x-1 transition-transform" />
          <span>Back to room details</span>
        </Link>

        {}
        <div className="mb-4">
        <h1 
            className="text-xl sm:text-2xl lg:text-3xl font-serif font-semibold 
              text-white mb-1.5 tracking-tight leading-tight
              bg-gradient-to-r from-white via-[#d4af37] to-white 
              bg-clip-text text-transparent"
        >
            Book Your Room
        </h1>
          <p className="text-gray-400 font-light tracking-wide text-xs sm:text-sm">
            Complete your reservation in just a few steps
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-3 sm:gap-4 lg:gap-6">
          {}
          <div className="lg:col-span-2">
            <form 
              onSubmit={handleSubmit(onSubmit)}
              className="bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] 
                rounded-lg border border-[#d4af37]/20 
                backdrop-blur-xl shadow-lg shadow-[#d4af37]/5 
                p-3 sm:p-4 space-y-4"
            >
              {}
              <div>
                <div className="flex items-center gap-2 mb-3">
                  <div className="p-1 bg-[#d4af37]/10 rounded-lg 
                    border border-[#d4af37]/30">
                    <Users className="w-3.5 h-3.5 text-[#d4af37]" />
                  </div>
                <h2 
                    className="text-sm sm:text-base font-serif font-semibold 
                      text-white tracking-wide"
                >
                  Customer Information
                </h2>
                </div>

                <div className="space-y-3">
                  {}
                  <div>
                    <label 
                      className="block text-[10px] sm:text-xs font-light tracking-wide
                        text-gray-300 mb-1"
                    >
                      Full Name
                      <span className="text-[#d4af37] ml-0.5">*</span>
                    </label>
                    <input
                      {...register('fullName')}
                      type="text"
                      className="w-full px-2.5 py-1.5 bg-[#0a0a0a] border 
                        border-[#d4af37]/20 rounded-lg 
                        text-white placeholder-gray-500 text-xs sm:text-sm
                        focus:ring-2 focus:ring-[#d4af37]/50 
                        focus:border-[#d4af37] transition-all duration-300
                        font-light tracking-wide"
                      placeholder="John Doe"
                    />
                    {errors.fullName && (
                      <p className="text-[10px] sm:text-xs text-red-400 mt-1 font-light">
                        {errors.fullName.message}
                      </p>
                    )}
                  </div>

                  {}
                  <div className="grid grid-cols-1 
                    md:grid-cols-2 gap-3"
                  >
                    <div>
                      <label 
                        className="block text-[10px] sm:text-xs font-light tracking-wide
                          text-gray-300 mb-1"
                      >
                        Email
                        <span className="text-[#d4af37] ml-0.5">*</span>
                      </label>
                      <input
                        {...register('email')}
                        type="email"
                        className="w-full px-2.5 py-1.5 bg-[#0a0a0a] border 
                          border-[#d4af37]/20 rounded-lg 
                          text-white placeholder-gray-500 text-xs sm:text-sm
                          focus:ring-2 focus:ring-[#d4af37]/50 
                          focus:border-[#d4af37] transition-all duration-300
                          font-light tracking-wide"
                        placeholder="email@example.com"
                      />
                      {errors.email && (
                        <p className="text-[10px] sm:text-xs text-red-400 
                          mt-1 font-light"
                        >
                          {errors.email.message}
                        </p>
                      )}
                    </div>

                    <div>
                      <label 
                        className="block text-[10px] sm:text-xs font-light tracking-wide
                          text-gray-300 mb-1"
                      >
                        Phone Number
                        <span className="text-[#d4af37] ml-0.5">*</span>
                      </label>
                      <input
                        {...register('phone')}
                        type="tel"
                        className="w-full px-2.5 py-1.5 bg-[#0a0a0a] border 
                          border-[#d4af37]/20 rounded-lg 
                          text-white placeholder-gray-500 text-xs sm:text-sm
                          focus:ring-2 focus:ring-[#d4af37]/50 
                          focus:border-[#d4af37] transition-all duration-300
                          font-light tracking-wide"
                        placeholder="0123456789"
                      />
                      {errors.phone && (
                        <p className="text-[10px] sm:text-xs text-red-400 
                          mt-1 font-light"
                        >
                          {errors.phone.message}
                        </p>
                      )}
                    </div>
                  </div>
                </div>
              </div>

              {}
              <div className="border-t border-[#d4af37]/20 pt-4">
                <div className="flex items-center gap-2 mb-3">
                  <div className="p-1 bg-[#d4af37]/10 rounded-lg 
                    border border-[#d4af37]/30">
                    <Calendar className="w-3.5 h-3.5 text-[#d4af37]" />
                  </div>
                <h2 
                    className="text-sm sm:text-base font-serif font-semibold 
                      text-white tracking-wide"
                >
                  Booking Details
                </h2>
                </div>

                <div className="space-y-3">
                  {}
                  <div className="grid grid-cols-1 
                    md:grid-cols-2 gap-3"
                  >
                    {}
                    <div>
                      <label 
                        className="block text-[10px] sm:text-xs font-light tracking-wide
                          text-gray-300 mb-1"
                      >
                        <Calendar 
                          className="w-3 h-3 inline mr-1 text-[#d4af37]" 
                        />
                        Check-in Date
                        <span className="text-[#d4af37] ml-0.5">*</span>
                      </label>
                      <Controller
                        control={control}
                        name="checkInDate"
                        render={({ field }) => (
                          <DatePicker
                            selected={field.value}
                            minDate={new Date()}
                            selectsStart
                            startDate={checkInDate}
                            endDate={checkOutDate}
                            dateFormat="dd/MM/yyyy"
                            placeholderText="Select check-in date"
                            excludeDates={bookedDates}
                            highlightDates={bookedDates.length > 0 ? bookedDates.map(date => {
                              
                              const normalized = new Date(date);
                              normalized.setHours(0, 0, 0, 0);
                              normalized.setMinutes(0, 0, 0);
                              return normalized;
                            }) : []}
                            dayClassName={(date) => {
                              
                              if (!date) return '';
                              const normalized = new Date(date);
                              normalized.setHours(0, 0, 0, 0);
                              normalized.setMinutes(0, 0, 0);
                              if (isDateBooked(normalized)) {
                                return 'react-datepicker__day--booked';
                              }
                              return '';
                            }}
                            filterDate={(date) => {
                              
                              if (isDateBooked(date)) {
                                return false;
                              }
                              
                              
                              if (checkOutDate) {
                                const testCheckIn = date;
                                const testCheckOut = checkOutDate;
                                if (testCheckIn < testCheckOut && doesRangeIncludeBookedDates(testCheckIn, testCheckOut)) {
                                  return false;
                                }
                              }
                              
                              return true;
                            }}
                            onChange={(date) => {
                              
                              if (date && isDateBooked(date)) {
                                toast.error('This date is already booked. Please select another date.');
                                return;
                              }
                              
                              
                              if (date && checkOutDate) {
                                const newCheckIn = date;
                                const newCheckOut = checkOutDate;
                                
                                if (newCheckIn < newCheckOut) {
                                  if (doesRangeIncludeBookedDates(newCheckIn, newCheckOut)) {
                                    toast.error('The selected date range includes booked dates. Please select different dates.');
                                    return;
                                  }
                                }
                              }
                              
                              field.onChange(date);
                            }}
                            className="w-full px-2.5 py-1.5 
                              bg-[#0a0a0a] border border-[#d4af37]/20 
                              rounded-lg text-white placeholder-gray-500 text-xs sm:text-sm
                              focus:ring-2 focus:ring-[#d4af37]/50 
                              focus:border-[#d4af37] transition-all duration-300
                              font-light tracking-wide"
                            wrapperClassName="w-full"
                          />
                        )}
                      />
                      {errors.checkInDate && (
                        <p className="text-[10px] sm:text-xs text-red-400 
                          mt-1 font-light"
                        >
                          {errors.checkInDate.message}
                        </p>
                      )}
                    </div>

                    {}
                    <div>
                      <label 
                        className="block text-[10px] sm:text-xs font-light tracking-wide
                          text-gray-300 mb-1"
                      >
                        <Calendar 
                          className="w-3 h-3 inline mr-1 text-[#d4af37]" 
                        />
                        Check-out Date
                        <span className="text-[#d4af37] ml-0.5">*</span>
                      </label>
                      <Controller
                        control={control}
                        name="checkOutDate"
                        render={({ field }) => (
                          <DatePicker
                            selected={field.value}
                            minDate={
                              checkInDate || new Date()
                            }
                            selectsEnd
                            startDate={checkInDate}
                            endDate={checkOutDate}
                            dateFormat="dd/MM/yyyy"
                            placeholderText="Select check-out date"
                            excludeDates={bookedDates}
                            highlightDates={bookedDates.length > 0 ? bookedDates.map(date => {
                              
                              const normalized = new Date(date);
                              normalized.setHours(0, 0, 0, 0);
                              normalized.setMinutes(0, 0, 0);
                              return normalized;
                            }) : []}
                            dayClassName={(date) => {
                              
                              if (!date) return '';
                              const normalized = new Date(date);
                              normalized.setHours(0, 0, 0, 0);
                              normalized.setMinutes(0, 0, 0);
                              if (isDateBooked(normalized)) {
                                return 'react-datepicker__day--booked';
                              }
                              return '';
                            }}
                            filterDate={(date) => {
                              
                              if (isDateBooked(date)) {
                                return false;
                              }
                              
                              
                              if (checkInDate) {
                                const testCheckIn = checkInDate;
                                const testCheckOut = date;
                                if (testCheckIn < testCheckOut && doesRangeIncludeBookedDates(testCheckIn, testCheckOut)) {
                                  return false;
                                }
                              }
                              
                              return true;
                            }}
                            onChange={(date) => {
                              
                              if (date && isDateBooked(date)) {
                                toast.error('This date is already booked. Please select another date.');
                                return;
                              }
                              
                              
                              if (date && checkInDate) {
                                const newCheckIn = checkInDate;
                                const newCheckOut = date;
                                
                                if (newCheckIn < newCheckOut) {
                                  if (doesRangeIncludeBookedDates(newCheckIn, newCheckOut)) {
                                    toast.error('The selected date range includes booked dates. Please select different dates.');
                                    return;
                                  }
                                }
                              }
                              
                              field.onChange(date);
                            }}
                            className="w-full px-2.5 py-1.5 
                              bg-[#0a0a0a] border border-[#d4af37]/20 
                              rounded-lg text-white placeholder-gray-500 text-xs sm:text-sm
                              focus:ring-2 focus:ring-[#d4af37]/50 
                              focus:border-[#d4af37] transition-all duration-300
                              font-light tracking-wide"
                            wrapperClassName="w-full"
                          />
                        )}
                      />
                      {errors.checkOutDate && (
                        <p className="text-[10px] sm:text-xs text-red-400 
                          mt-1 font-light"
                        >
                          {errors.checkOutDate.message}
                        </p>
                      )}
                    </div>
                  </div>

                  {}
                  <div>
                    <label 
                      className="block text-[10px] sm:text-xs font-light tracking-wide
                        text-gray-300 mb-1"
                    >
                      <Users 
                        className="w-3 h-3 inline mr-1 text-[#d4af37]" 
                      />
                      Number of Guests
                      <span className="text-[#d4af37] ml-0.5">*</span>
                    </label>
                    <input
                      {...register('guestCount')}
                      type="number"
                      min="1"
                      max={room?.capacity || roomType.capacity}
                      className="w-full px-2.5 py-1.5 bg-[#0a0a0a] border 
                        border-[#d4af37]/20 rounded-lg 
                        text-white placeholder-gray-500 text-xs sm:text-sm
                        focus:ring-2 focus:ring-[#d4af37]/50 
                        focus:border-[#d4af37] transition-all duration-300
                        font-light tracking-wide"
                      placeholder="1"
                    />
                    <p className="text-[10px] sm:text-xs text-gray-400 mt-1 font-light tracking-wide">
                      Maximum capacity: <span className="text-[#d4af37]">{room?.capacity || roomType.capacity}</span> guests
                    </p>
                    {errors.guestCount && (
                      <p className="text-[10px] sm:text-xs text-red-400 mt-1 font-light">
                        {errors.guestCount.message}
                      </p>
                    )}
                  </div>

                  {}
                  <div>
                    <label 
                      className="block text-[10px] sm:text-xs font-light tracking-wide
                        text-gray-300 mb-1"
                    >
                      <FileText 
                        className="w-3 h-3 inline mr-1 text-[#d4af37]" 
                      />
                      Notes (optional)
                    </label>
                    <textarea
                      {...register('notes')}
                      rows={2}
                      className="w-full px-2.5 py-1.5 bg-[#0a0a0a] border 
                        border-[#d4af37]/20 rounded-lg 
                        text-white placeholder-gray-500 text-xs sm:text-sm
                        focus:ring-2 focus:ring-[#d4af37]/50 
                        focus:border-[#d4af37] transition-all duration-300
                        font-light tracking-wide resize-none"
                      placeholder="Special requests..."
                    />
                    {errors.notes && (
                      <p className="text-[10px] sm:text-xs text-red-400 mt-1 font-light">
                        {errors.notes.message}
                      </p>
                    )}
                  </div>
                </div>
              </div>

              {}
              {services.length > 0 && (
                <div className="border-t border-[#d4af37]/20 pt-4">
                  <div className="flex items-center gap-2 mb-3">
                    <div className="p-1 bg-[#d4af37]/10 rounded-lg 
                      border border-[#d4af37]/30">
                      <Sparkles className="w-3.5 h-3.5 text-[#d4af37]" />
                    </div>
                    <h2 
                      className="text-sm sm:text-base font-serif font-semibold 
                        text-white tracking-wide"
                    >
                      Additional Services
                    </h2>
                  </div>
                  <p className="text-gray-400 text-xs sm:text-sm mb-3 font-light tracking-wide">
                    Enhance your stay with our premium services (optional)
                  </p>

                  <div className="space-y-2.5 sm:space-y-3">
                    {services.map((service) => {
                      const selectedItem = selectedServices.find(
                        item => item.service.id === service.id
                      );
                      const quantity = selectedItem?.quantity || 0;

                      return (
                        <div
                          key={service.id}
                          className="bg-gradient-to-br from-[#0a0a0a] to-[#1a1a1a]
                            border border-[#d4af37]/20 rounded-lg p-3
                            hover:border-[#d4af37]/40 transition-all duration-300"
                        >
                          <div className="flex items-start justify-between mb-2">
                            <div className="flex-1">
                              <h3 className="text-white font-semibold mb-0.5 text-sm">
                                {service.name}
                              </h3>
                              {service.description && (
                                <p className="text-gray-400 text-xs mb-1">
                                  {service.description}
                                </p>
                              )}
                              <p className="text-[#d4af37] font-bold text-xs sm:text-sm">
                                {formatPrice(service.price)} / {service.unit || 'unit'}
                              </p>
                            </div>
                          </div>

                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-2">
                              <button
                                type="button"
                                onClick={() => {
                                  if (quantity > 0) {
                                    if (quantity === 1) {
                                      setSelectedServices(prev =>
                                        prev.filter(item => item.service.id !== service.id)
                                      );
                                    } else {
                                      setSelectedServices(prev =>
                                        prev.map(item =>
                                          item.service.id === service.id
                                            ? { ...item, quantity: item.quantity - 1 }
                                            : item
                                        )
                                      );
                                    }
                                  }
                                }}
                                disabled={quantity === 0}
                                className="w-7 h-7 flex items-center justify-center 
                                  bg-[#1a1a1a] border border-[#d4af37]/20 
                                  rounded text-[#d4af37] hover:bg-[#d4af37]/10 
                                  transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                              >
                                <Minus className="w-3.5 h-3.5" />
                              </button>
                              <span className="text-white font-semibold w-6 text-center text-sm">
                                {quantity}
                              </span>
                              <button
                                type="button"
                                onClick={() => {
                                  if (quantity === 0) {
                                    setSelectedServices(prev => [
                                      ...prev,
                                      { service, quantity: 1 }
                                    ]);
                                  } else {
                                    setSelectedServices(prev =>
                                      prev.map(item =>
                                        item.service.id === service.id
                                          ? { ...item, quantity: item.quantity + 1 }
                                          : item
                                      )
                                    );
                                  }
                                }}
                                className="w-7 h-7 flex items-center justify-center 
                                  bg-[#1a1a1a] border border-[#d4af37]/20 
                                  rounded text-[#d4af37] hover:bg-[#d4af37]/10 
                                  transition-colors"
                              >
                                <Plus className="w-3.5 h-3.5" />
                              </button>
                            </div>
                            {quantity > 0 && (
                              <p className="text-[#d4af37] font-bold text-sm">
                                {formatPrice(service.price * quantity)}
                              </p>
                            )}
                          </div>
                        </div>
                      );
                    })}
                  </div>

                  {selectedServices.length > 0 && (
                    <div className="mt-4 pt-4 border-t border-[#d4af37]/20">
                      <div className="flex items-center justify-between">
                        <span className="text-xs sm:text-sm text-gray-400 font-light">Services Total:</span>
                        <span className="text-base sm:text-lg font-bold text-[#d4af37]">
                          {formatPrice(servicesTotal)}
                        </span>
                      </div>
                    </div>
                  )}
                </div>
              )}

              {}
              <div className="border-t border-[#d4af37]/20 pt-4">
                <div className="flex items-center gap-2 mb-3">
                  <div className="p-1 bg-[#d4af37]/10 rounded-lg border border-[#d4af37]/30">
                    <Sparkles className="w-3.5 h-3.5 text-[#d4af37]" />
                  </div>
                  <h2 className="text-sm sm:text-base font-serif font-semibold text-white tracking-wide">
                    Promotion Code
                  </h2>
                </div>
                <p className="text-gray-400 text-xs sm:text-sm mb-3 font-light tracking-wide">
                  Enter a promotion code to get a discount (optional)
                </p>

                {!selectedPromotion ? (
                  <div className="space-y-2">
                    <div className="flex gap-2">
                      <input
                        type="text"
                        value={promotionCode}
                        onChange={(e) => {
                          setPromotionCode(e.target.value.toUpperCase());
                          setPromotionError(null);
                        }}
                        onKeyPress={(e) => {
                          if (e.key === 'Enter') {
                            e.preventDefault();
                            handleValidatePromotion();
                          }
                        }}
                        placeholder="Enter promotion code"
                        className="flex-1 px-4 py-2.5 bg-[#0a0a0a] border border-[#d4af37]/20 
                          rounded-lg text-white placeholder-gray-500 focus:outline-none 
                          focus:border-[#d4af37]/40 focus:ring-2 focus:ring-[#d4af37]/20 
                          transition-all duration-300 text-sm sm:text-base"
                        disabled={validatingPromotion || subtotal === 0}
                      />
                      <button
                        type="button"
                        onClick={handleValidatePromotion}
                        disabled={validatingPromotion || !promotionCode.trim() || subtotal === 0}
                        className="px-4 py-2.5 bg-gradient-to-r from-[#d4af37] to-[#c9a227] 
                          text-black font-semibold rounded-lg hover:from-[#c9a227] 
                          hover:to-[#d4af37] transition-all duration-300 disabled:opacity-50 
                          disabled:cursor-not-allowed text-sm sm:text-base flex items-center gap-2"
                      >
                        {validatingPromotion ? (
                          <>
                            <Loader2 className="w-4 h-4 animate-spin" />
                            <span>Validating...</span>
                          </>
                        ) : (
                          'Apply'
                        )}
                      </button>
                    </div>
                    {promotionError && (
                      <p className="text-red-400 text-xs sm:text-sm">{promotionError}</p>
                    )}
                    {subtotal === 0 && (
                      <p className="text-yellow-400 text-xs sm:text-sm">
                        Please select check-in and check-out dates first
                      </p>
                    )}
                  </div>
                ) : (
                  <div className="bg-gradient-to-br from-green-900/20 to-green-800/10 
                    border border-green-500/30 rounded-lg p-3">
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <CheckCircle className="w-4 h-4 text-green-400" />
                          <span className="text-green-400 font-semibold text-sm sm:text-base">
                            {selectedPromotion.name}
                          </span>
                        </div>
                        {selectedPromotion.description && (
                          <p className="text-gray-400 text-xs mb-2">
                            {selectedPromotion.description}
                          </p>
                        )}
                        <div className="flex items-center gap-2">
                          <span className="text-xs sm:text-sm text-gray-400">Code:</span>
                          <span className="text-xs sm:text-sm font-mono font-bold text-[#d4af37]">
                            {selectedPromotion.code}
                          </span>
                        </div>
                        <div className="mt-2">
                          <span className="text-xs sm:text-sm text-gray-400">Discount: </span>
                          <span className="text-sm sm:text-base font-bold text-green-400">
                            -{formatPrice(promotionDiscount)}
                          </span>
                        </div>
                      </div>
                      <button
                        type="button"
                        onClick={handleRemovePromotion}
                        className="p-1.5 hover:bg-red-500/20 rounded-lg transition-colors"
                        title="Remove promotion"
                      >
                        <X className="w-4 h-4 text-red-400" />
                      </button>
                    </div>
                  </div>
                )}
              </div>

              {}
              <div className="border-t border-[#d4af37]/20 pt-4">
                <div className="flex items-center gap-2 mb-3">
                  <div className="p-1 bg-[#d4af37]/10 rounded-lg 
                    border border-[#d4af37]/30">
                    <CreditCard className="w-3.5 h-3.5 text-[#d4af37]" />
                  </div>
                <h2 
                    className="text-sm sm:text-base font-serif font-semibold 
                      text-white tracking-wide"
                >
                  Payment Method
                </h2>
                </div>

                <div className="space-y-2.5">
                  {}
                  <label 
                    className="flex items-start p-3 
                      bg-gradient-to-br from-[#0a0a0a] to-[#1a1a1a]
                      border-2 border-[#d4af37]/20 
                      rounded-lg cursor-pointer 
                      hover:border-[#d4af37]/40 hover:shadow-md hover:shadow-[#d4af37]/10
                      transition-all duration-300"
                  >
                    <input
                      {...register('paymentMethod')}
                      type="radio"
                      value="cash"
                      className="mt-0.5 mr-3 w-4 h-4 text-[#d4af37] 
                        border-[#d4af37]/30 focus:ring-[#d4af37]/50"
                    />
                    <div className="flex-1">
                      <div className="flex items-center flex-wrap
                        gap-2 mb-1.5"
                      >
                        <CreditCard 
                          className="w-3.5 h-3.5 
                            text-[#d4af37]" 
                        />
                        <span className="font-medium 
                          text-white tracking-wide text-xs sm:text-sm"
                        >
                          Pay on arrival
                        </span>
                        <span className="text-[10px] sm:text-xs bg-gradient-to-r 
                          from-orange-900/30 to-orange-800/20 
                          text-orange-300 border border-orange-500/30
                          px-2 py-0.5 rounded font-medium tracking-wide"
                        >
                          Requires 20% deposit
                        </span>
                      </div>
                      <p className="text-xs text-gray-400 mb-2 font-light tracking-wide">
                        Requires 20% deposit, remaining balance on arrival
                      </p>
                      <div className="bg-gradient-to-br from-orange-900/20 to-orange-800/10 
                        border border-orange-500/30 rounded-lg p-2.5"
                      >
                        <p className="text-[10px] sm:text-xs text-orange-300 font-light tracking-wide leading-relaxed">
                          <strong className="text-orange-200">20% deposit required</strong> to secure your booking. Pay the remaining balance on arrival at the hotel.
                        </p>
                      </div>
                    </div>
                  </label>

                  {}
                  <label 
                    className="flex items-start p-3 
                      bg-gradient-to-br from-[#0a0a0a] to-[#1a1a1a]
                      border-2 border-[#d4af37]/20 
                      rounded-lg cursor-pointer 
                      hover:border-[#d4af37]/40 hover:shadow-md hover:shadow-[#d4af37]/10
                      transition-all duration-300"
                  >
                    <input
                      {...register('paymentMethod')}
                      type="radio"
                      value="stripe"
                      className="mt-0.5 mr-3 w-4 h-4 text-[#d4af37] 
                        border-[#d4af37]/30 focus:ring-[#d4af37]/50"
                    />
                    <div className="flex-1">
                      <div className="flex items-center flex-wrap
                        gap-2 mb-1"
                      >
                        <CreditCard 
                          className="w-3.5 h-3.5 
                            text-[#d4af37]" 
                        />
                        <span className="font-medium 
                          text-white tracking-wide text-xs sm:text-sm"
                        >
                          Pay with Card (Stripe)
                        </span>
                        <span className="text-[10px] sm:text-xs bg-gradient-to-r 
                          from-[#d4af37]/20 to-[#c9a227]/20 
                          text-[#d4af37] border border-[#d4af37]/40
                          px-2 py-0.5 rounded font-medium tracking-wide"
                        >
                          Instant
                        </span>
                      </div>
                      <p className="text-xs text-gray-400 font-light tracking-wide">
                        Secure payment with credit or debit card
                      </p>
                    </div>
                  </label>

                  {errors.paymentMethod && (
                    <p className="text-[10px] sm:text-xs text-red-400 font-light">
                      {errors.paymentMethod.message}
                    </p>
                  )}

                  {}
                  <label 
                    className="flex items-start p-3 
                      bg-gradient-to-br from-[#0a0a0a] to-[#1a1a1a]
                      border-2 border-[#d4af37]/20 
                      rounded-lg cursor-pointer 
                      hover:border-[#d4af37]/40 hover:shadow-md hover:shadow-[#d4af37]/10
                      transition-all duration-300"
                  >
                    <input
                      {...register('paymentMethod')}
                      type="radio"
                      value="paypal"
                      className="mt-0.5 mr-3 w-4 h-4 text-[#d4af37] 
                        border-[#d4af37]/30 focus:ring-[#d4af37]/50"
                    />
                    <div className="flex-1">
                      <div className="flex items-center flex-wrap
                        gap-2 mb-1"
                      >
                        <CreditCard 
                          className="w-3.5 h-3.5 
                            text-[#d4af37]" 
                        />
                        <span className="font-medium 
                          text-white tracking-wide text-xs sm:text-sm"
                        >
                          Pay with PayPal
                        </span>
                        <span className="text-[10px] sm:text-xs bg-gradient-to-r 
                          from-[#d4af37]/20 to-[#c9a227]/20 
                          text-[#d4af37] border border-[#d4af37]/40
                          px-2 py-0.5 rounded font-medium tracking-wide"
                        >
                          Instant
                        </span>
                      </div>
                      <p className="text-xs text-gray-400 font-light tracking-wide">
                        Secure payment with PayPal account
                      </p>
                    </div>
                  </label>

                  {}
                  {paymentMethod === 'stripe' && (
                    <div 
                      className="bg-gradient-to-br from-[#d4af37]/10 to-[#c9a227]/5 
                        border border-[#d4af37]/30 rounded-lg 
                        p-3 mt-2 backdrop-blur-sm"
                    >
                      <div className="flex items-center gap-2 mb-2">
                        <Shield className="w-3.5 h-3.5 text-[#d4af37]" />
                        <p className="text-xs sm:text-sm text-[#d4af37] 
                          font-medium tracking-wide"
                      >
                          Secure Card Payment
                      </p>
                      </div>
                      <p className="text-xs text-gray-300 font-light tracking-wide leading-relaxed">
                        You will be redirected to a secure payment page 
                        to complete your booking with your credit or debit card.
                      </p>
                    </div>
                  )}

                  {}
                  {paymentMethod === 'paypal' && (
                    <div 
                      className="bg-gradient-to-br from-[#d4af37]/10 to-[#c9a227]/5 
                        border border-[#d4af37]/30 rounded-lg 
                        p-3 mt-2 backdrop-blur-sm"
                    >
                      <div className="flex items-center gap-2 mb-2">
                        <Shield className="w-3.5 h-3.5 text-[#d4af37]" />
                        <p className="text-xs sm:text-sm text-[#d4af37] 
                          font-medium tracking-wide"
                      >
                          Secure PayPal Payment
                      </p>
                      </div>
                      <p className="text-xs text-gray-300 font-light tracking-wide leading-relaxed">
                        You will be redirected to PayPal to securely complete your payment.
                      </p>
                    </div>
                  )}
                </div>
              </div>

              {}
              <div className="border-t border-[#d4af37]/20 pt-4">
                <div className="flex items-center gap-2 mb-3">
                  <div className="p-1 bg-[#d4af37]/10 rounded-lg 
                    border border-[#d4af37]/30">
                    <FileText className="w-3.5 h-3.5 text-[#d4af37]" />
                  </div>
                  <h2 
                    className="text-sm sm:text-base font-serif font-semibold 
                      text-white tracking-wide"
                  >
                    Invoice Information (Optional)
                  </h2>
                </div>

                <div className="space-y-3">
                  <p className="text-[10px] sm:text-xs text-gray-400 font-light">
                    Fill in these details if you need an invoice for your booking
                  </p>

                  {}
                  <div>
                    <label className="block text-[10px] sm:text-xs font-light 
                      text-gray-300 mb-1 tracking-wide"
                    >
                      Company Name
                    </label>
                    <input
                      {...register('invoiceInfo.company_name')}
                      type="text"
                      className="w-full px-2.5 py-1.5 bg-[#0a0a0a] border 
                        border-[#d4af37]/20 rounded-lg 
                        text-white placeholder-gray-500 text-xs sm:text-sm
                        focus:ring-2 focus:ring-[#d4af37]/50 
                        focus:border-[#d4af37] transition-all duration-300
                        font-light tracking-wide"
                      placeholder="Your company name"
                    />
                  </div>

                  {}
                  <div>
                    <label className="block text-[10px] sm:text-xs font-light 
                      text-gray-300 mb-1 tracking-wide"
                    >
                      Company Address
                    </label>
                    <textarea
                      {...register('invoiceInfo.company_address')}
                      rows={2}
                      className="w-full px-2.5 py-1.5 bg-[#0a0a0a] border 
                        border-[#d4af37]/20 rounded-lg 
                        text-white placeholder-gray-500 text-xs sm:text-sm
                        focus:ring-2 focus:ring-[#d4af37]/50 
                        focus:border-[#d4af37] transition-all duration-300
                        font-light tracking-wide resize-none"
                      placeholder="Company address"
                    />
                  </div>

                  {}
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div>
                      <label className="block text-[10px] sm:text-xs font-light 
                        text-gray-300 mb-1 tracking-wide"
                      >
                        Company Tax ID
                      </label>
                      <input
                        {...register('invoiceInfo.company_tax_id')}
                        type="text"
                        className="w-full px-2.5 py-1.5 bg-[#0a0a0a] border 
                          border-[#d4af37]/20 rounded-lg 
                          text-white placeholder-gray-500 text-xs sm:text-sm
                          focus:ring-2 focus:ring-[#d4af37]/50 
                          focus:border-[#d4af37] transition-all duration-300
                          font-light tracking-wide"
                        placeholder="Tax ID"
                      />
                    </div>

                    <div>
                      <label className="block text-[10px] sm:text-xs font-light 
                        text-gray-300 mb-1 tracking-wide"
                      >
                        Customer Tax ID
                      </label>
                      <input
                        {...register('invoiceInfo.customer_tax_id')}
                        type="text"
                        className="w-full px-2.5 py-1.5 bg-[#0a0a0a] border 
                          border-[#d4af37]/20 rounded-lg 
                          text-white placeholder-gray-500 text-xs sm:text-sm
                          focus:ring-2 focus:ring-[#d4af37]/50 
                          focus:border-[#d4af37] transition-all duration-300
                          font-light tracking-wide"
                        placeholder="Your tax ID"
                      />
                    </div>
                  </div>

                </div>
              </div>

              {}
              <div className="border-t border-[#d4af37]/20 pt-4">
                <div className="flex justify-center mb-4">
                  <Recaptcha
                    onChange={(token) => setRecaptchaToken(token)}
                    onError={(error) => {
                      console.error('reCAPTCHA error:', error);
                      setRecaptchaToken(null);
                    }}
                    theme="dark"
                    size="normal"
                  />
                </div>
              </div>

              {}
              <div className="border-t border-[#d4af37]/20 pt-4">
                <button
                  type="submit"
                  disabled={submitting}
                  className="w-full bg-gradient-to-r from-[#d4af37] to-[#c9a227] 
                    text-[#0f0f0f] py-2.5 rounded-sm 
                    hover:from-[#f5d76e] hover:to-[#d4af37] 
                    transition-all duration-300 font-medium 
                    text-sm sm:text-base disabled:bg-gray-800 disabled:text-gray-500
                    disabled:cursor-not-allowed disabled:hover:from-gray-800
                    disabled:hover:to-gray-800
                    flex items-center justify-center 
                    gap-2 relative overflow-hidden group
                    shadow-md shadow-[#d4af37]/30 hover:shadow-[#d4af37]/50
                    tracking-wide"
                >
                  {submitting ? (
                    <>
                      <Loader2 
                        className="w-4 h-4 animate-spin relative z-10" 
                      />
                      <span className="relative z-10">Processing...</span>
                    </>
                  ) : (
                    <>
                      <span className="relative z-10">Confirm Booking</span>
                      <CheckCircle className="w-4 h-4 relative z-10" />
                    </>
                  )}
                  {!submitting && (
                    <span className="absolute inset-0 bg-gradient-to-r from-white/0 via-white/20 to-white/0 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-700"></span>
                  )}
                </button>
              </div>
            </form>
          </div>

          {}
          <div className="lg:col-span-1">
            <div 
              className="bg-gradient-to-br from-[#1a1a1a] via-[#0f0f0f] to-[#1a1a1a] 
                rounded-lg border border-[#d4af37]/30 
                backdrop-blur-xl shadow-lg shadow-[#d4af37]/20 
                p-3 sm:p-4 sticky top-4"
            >
              <div className="flex items-center gap-2 mb-4">
                <div className="p-1 bg-[#d4af37]/10 rounded-lg 
                  border border-[#d4af37]/30">
                  <Sparkles className="w-3.5 h-3.5 text-[#d4af37]" />
                </div>
              <h2 
                  className="text-sm sm:text-base font-serif font-semibold 
                    text-white tracking-wide"
              >
                Booking Summary
              </h2>
              </div>

              {}
              <div className="mb-4">
                {((room?.images && room.images.length > 0) 
                  ? room.images[0] 
                  : roomType.images?.[0]) && (
                  <div className="relative overflow-hidden rounded-lg mb-3 
                    border border-[#d4af37]/20 group"
                  >
                  <img
                    src={(room?.images && room.images.length > 0) 
                      ? room.images[0] 
                      : (roomType.images?.[0] || '')}
                    alt={roomType.name}
                    className="w-full h-32 sm:h-40 object-cover 
                        group-hover:scale-110 transition-transform 
                        duration-500"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t 
                      from-black/60 via-transparent to-transparent 
                      opacity-0 group-hover:opacity-100 transition-opacity 
                      duration-300"
                  />
                  </div>
                )}
                <h3 className="font-serif font-semibold text-white mb-1.5 
                  text-sm sm:text-base tracking-tight"
                >
                  {roomType.name}
                </h3>
                <div className="flex items-center gap-1.5 text-gray-400 
                  font-light tracking-wide text-xs sm:text-sm"
                >
                  <MapPin className="w-3.5 h-3.5 text-[#d4af37]" />
                  <span>
                  Room {room.room_number} - Floor {room.floor}
                  </span>
                </div>
              </div>

              {}
              <div className="border-t border-[#d4af37]/20 pt-4 space-y-2">
                <div className="flex justify-between items-center">
                  <span className="text-[10px] sm:text-xs text-gray-400 font-light tracking-wide">
                    Room price/night
                  </span>
                  <span className="font-light text-white text-xs sm:text-sm">
                    {formatPrice(roomPrice)}
                  </span>
                </div>

                {numberOfNights > 0 && (
                  <div className="flex justify-between items-center">
                    <span className="text-[10px] sm:text-xs text-gray-400 font-light tracking-wide">
                      Nights
                    </span>
                    <span className="font-light text-white text-xs sm:text-sm">
                      {numberOfNights} night(s)
                    </span>
                  </div>
                )}

                {numberOfNights > 0 && (
                  <div className="flex justify-between items-center">
                    <span className="text-[10px] sm:text-xs text-gray-400 font-light tracking-wide">
                      Room Total
                    </span>
                    <span className="font-light text-white text-xs sm:text-sm">
                      {formatPrice(roomTotal)}
                    </span>
                  </div>
                )}

                {selectedServices.length > 0 && (
                  <>
                    <div className="border-t border-[#d4af37]/20 pt-2 mt-2">
                      <p className="text-[10px] sm:text-xs text-gray-400 font-light tracking-wide mb-1.5">
                        Services:
                      </p>
                      {selectedServices.map((item) => (
                        <div key={item.service.id} className="flex justify-between items-center mb-1">
                          <span className="text-[10px] sm:text-xs text-gray-500 font-light tracking-wide">
                            {item.service.name} (×{item.quantity})
                          </span>
                          <span className="font-light text-white text-[10px] sm:text-xs">
                            {formatPrice(item.service.price * item.quantity)}
                          </span>
                        </div>
                      ))}
                      <div className="flex justify-between items-center mt-1.5 pt-1.5 border-t border-[#d4af37]/10">
                        <span className="text-[10px] sm:text-xs text-gray-400 font-light tracking-wide">
                          Services Total
                        </span>
                        <span className="font-light text-white text-xs sm:text-sm">
                          {formatPrice(servicesTotal)}
                        </span>
                      </div>
                    </div>
                  </>
                )}

                {numberOfNights > 0 && (
                  <div className="border-t border-[#d4af37]/20 pt-2 mt-2">
                    <div className="flex justify-between items-center mb-1">
                      <span className="text-[10px] sm:text-xs text-gray-400 font-light tracking-wide">
                        Subtotal
                      </span>
                      <span className="font-light text-white text-xs sm:text-sm">
                        {formatPrice(subtotal)}
                      </span>
                    </div>
                  </div>
                )}

                {selectedPromotion && promotionDiscount > 0 && numberOfNights > 0 && (
                  <div className="border-t border-[#d4af37]/20 pt-2 mt-2">
                    <div className="flex justify-between items-center">
                      <span className="text-[10px] sm:text-xs text-green-400 font-light tracking-wide">
                        Promotion Discount ({selectedPromotion.code})
                      </span>
                      <span className="font-light text-green-400 text-xs sm:text-sm">
                        -{formatPrice(promotionDiscount)}
                      </span>
                    </div>
                  </div>
                )}

                <div 
                  className="border-t border-[#d4af37]/20 pt-3 flex 
                    justify-between items-center"
                >
                  <span className="text-sm sm:text-base font-medium text-white tracking-wide">Total</span>
                  <span className="text-lg sm:text-xl font-serif font-semibold 
                    bg-gradient-to-r from-[#d4af37] to-[#f5d76e] 
                    bg-clip-text text-transparent tracking-tight"
                  >
                    {numberOfNights > 0
                      ? formatPrice(totalPrice)
                      : '---'}
                  </span>
                </div>

                {}
                {paymentMethod === 'cash' && numberOfNights > 0 && (
                  <div className="bg-gradient-to-br from-orange-900/20 to-orange-800/10 
                    border border-orange-500/30 rounded-lg p-3 mt-3"
                  >
                    <div className="flex justify-between 
                      items-center mb-1.5"
                    >
                      <span className="text-xs sm:text-sm font-medium 
                        text-orange-300 tracking-wide"
                      >
                        Deposit to pay (20%)
                      </span>
                      <span className="text-base sm:text-lg font-display font-semibold 
                        text-[#d4af37] tracking-tight"
                      >
                        {formatPrice(totalPrice * 0.2)}
                      </span>
                    </div>
                    <p className="text-[10px] sm:text-xs text-orange-300/80 font-light tracking-wide">
                      Pay 20% deposit to secure booking, remaining balance on arrival
                    </p>
                  </div>
                )}
              </div>

              {}
              <div 
                className={`border rounded-lg p-2.5 sm:p-3 mt-3 ${
                  paymentMethod === 'cash'
                    ? 'bg-gradient-to-br from-orange-900/20 to-orange-800/10 border-orange-500/30'
                    : 'bg-gradient-to-br from-[#d4af37]/10 to-[#c9a227]/5 border-[#d4af37]/30'
                }`}
              >
                {paymentMethod === 'cash' ? (
                  <div className="flex items-start gap-2">
                    <Shield className="w-3.5 h-3.5 text-orange-400 mt-0.5 flex-shrink-0" />
                    <p className="text-[10px] sm:text-xs text-orange-300 font-light tracking-wide leading-relaxed">
                        <strong className="text-orange-200">20% deposit required</strong> to secure your booking. Pay the remaining balance ({formatPrice(totalPrice * 0.8)}) on arrival at the hotel.
                  </p>
                  </div>
                ) : (
                  <div className="flex items-start gap-2">
                    <Sparkles className="w-3.5 h-3.5 text-[#d4af37] mt-0.5 flex-shrink-0" />
                    <p className="text-[10px] sm:text-xs text-gray-300 font-light tracking-wide leading-relaxed">
                      Secure payment via Stripe. Complete your booking 
                      with credit or debit card after confirming.
                  </p>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default BookingPage;
