import React, { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import {
  Users,
  MapPin,
  ArrowLeft,
  Star,
  Calendar,
  Shield,
  Award,
  Sparkles,
} from 'lucide-react';
import { getRoomByNumber, getRoomBookedDates, type Room } from '../../features/rooms/services/roomService';
import RoomGallery from '../../features/rooms/components/RoomGallery';
import RoomAmenities from '../../features/rooms/components/RoomAmenities';
import ReviewSection from '../../features/rooms/components/ReviewSection';
import CurrencyIcon from '../../shared/components/CurrencyIcon';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';
import useAuthStore from '../../store/useAuthStore';
import LuxuryBookingModal from '../../features/bookings/components/LuxuryBookingModal';
import { useAuthModal } from '../../features/auth/contexts/AuthModalContext';
import { toast } from 'react-toastify';
import { logger } from '../../shared/utils/logger';
import { useTheme } from '../../shared/contexts/ThemeContext';
import { getThemeBackgroundClasses, getThemeTextClasses, getThemeCardClasses } from '../../shared/utils/themeUtils';

const RoomDetailPage: React.FC = () => {
  const { theme } = useTheme();
  const textClasses = getThemeTextClasses(theme.theme_layout_mode);
  const bgClasses = getThemeBackgroundClasses(theme.theme_layout_mode);
  const cardClasses = getThemeCardClasses(theme.theme_layout_mode);
  const { room_number } = useParams<{ room_number: string }>();
  const navigate = useNavigate();
  const { formatCurrency } = useFormatCurrency();
  const { userInfo, isAuthenticated } = useAuthStore();
  const { openModal } = useAuthModal();
  const [room, setRoom] = useState<Room | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showBookingModal, setShowBookingModal] = useState(false);
  const [nextAvailableDate, setNextAvailableDate] = useState<Date | null>(null);
  const [bookedUntilDate, setBookedUntilDate] = useState<Date | null>(null);
  const abortControllerRef = useRef<AbortController | null>(null);

  useEffect(() => {
    if (!room_number) {
      return;
    }

    // Cancel previous request if exists
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }

    // Create new abort controller
    abortControllerRef.current = new AbortController();

    fetchRoomDetail(room_number);

    // Cleanup: abort request on unmount
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [room_number]);

  const fetchRoomDetail = async (roomNumber: string) => {
    try {
      setLoading(true);
      setError(null);
      const response = await getRoomByNumber(roomNumber);
      
      if (response.success || response.status === 'success') {
        if (response.data && response.data.room) {
          const fetchedRoom = response.data.room;
          
          if (fetchedRoom.room_number !== roomNumber) {
            // Log room number mismatch for debugging
            logger.error('Room number mismatch', new Error('Room data mismatch'), {
              requested: roomNumber,
              received: fetchedRoom.room_number
            });
            throw new Error(`Room data mismatch: expected room number ${roomNumber} but got ${fetchedRoom.room_number}`);
          }
          
          setRoom(fetchedRoom);
          
          // Fetch booked dates to calculate availability
          if (fetchedRoom.id) {
            await fetchBookedDates(fetchedRoom.id);
          }
        } else {
          throw new Error('Failed to fetch room details');
        }
      } else {
        throw new Error('Failed to fetch room details');
      }
    } catch (err: unknown) {
      const isAbortError = (e: unknown): boolean => {
        if (typeof e === 'object' && e !== null) {
          const error = e as { name?: string; code?: string };
          return error.name === 'AbortError' || error.code === 'ERR_CANCELED';
        }
        return false;
      };
      if (isAbortError(err)) {
        return;
      }
      logger.error('Error fetching room', err);
      const message =
        getUserFriendlyError(err) ||
        'Unable to load room information';
      setError(message);
    } finally {
      setLoading(false);
    }
  };

  const fetchBookedDates = async (roomId: number) => {
    try {
      const response = await getRoomBookedDates(roomId);
      if (response.success && response.data?.booked_dates) {
        const bookedDates = response.data.booked_dates.map((date: string) => {
          const d = new Date(date);
          d.setHours(0, 0, 0, 0);
          return d;
        });
        
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        
        // Sort booked dates
        const sortedBookedDates = bookedDates.sort((a: Date, b: Date) => a.getTime() - b.getTime());
        
        // Find if today is booked
        const todayBooked = sortedBookedDates.some((date: Date) => {
          return date.getTime() === today.getTime();
        });
        
        if (todayBooked) {
          // Find consecutive booked dates starting from today
          let lastConsecutiveDate = new Date(today);
          
          for (let i = 0; i < sortedBookedDates.length; i++) {
            const bookedDate = sortedBookedDates[i];
            
            // Check if this date is consecutive from the last found date
            const daysDiff = Math.floor((bookedDate.getTime() - lastConsecutiveDate.getTime()) / (1000 * 60 * 60 * 24));
            
            if (daysDiff === 0 || daysDiff === 1) {
              // This date is part of the consecutive booking
              lastConsecutiveDate = new Date(bookedDate);
            } else if (daysDiff > 1) {
              // Gap found, stop looking
              break;
            }
          }
          
          // Set booked until date (check-out date is the last booked date)
          setBookedUntilDate(lastConsecutiveDate);
          
          // Next available date is the day after the last booked date
          const nextAvailable = new Date(lastConsecutiveDate);
          nextAvailable.setDate(nextAvailable.getDate() + 1);
          setNextAvailableDate(nextAvailable);
        } else {
          // Today is not booked, so it's available now
          setNextAvailableDate(today);
          setBookedUntilDate(null);
        }
      }
    } catch (err: unknown) {
      const isAbortError = (e: unknown): boolean => {
        if (typeof e === 'object' && e !== null) {
          const error = e as { name?: string; code?: string };
          return error.name === 'AbortError' || error.code === 'ERR_CANCELED';
        }
        return false;
      };
      if (isAbortError(err)) {
        return;
      }
      logger.error('Error fetching booked dates', err);
      // Don't show error to user, just don't show availability info
    }
  };

  if (loading) {
    return (
      <div 
        className={`min-h-screen ${bgClasses} w-screen relative -mt-6 -mb-6`}
        style={{ 
          marginLeft: 'calc(50% - 50vw)',
          marginRight: 'calc(50% - 50vw)',
          width: '100vw',
          paddingTop: '1.5rem',
          paddingBottom: '1.5rem',
          zIndex: 1
        }}
      >
        <div className="w-full px-2 sm:px-4 md:px-6 lg:px-8 py-8 sm:py-12">
          <div className="animate-pulse space-y-6">
            <div className={`h-[600px] ${cardClasses} rounded-xl border border-[var(--luxury-gold)]/20`} />
            <div className={`h-12 ${cardClasses} rounded-lg w-1/3 border border-[var(--luxury-gold)]/10`} />
            <div className={`h-6 ${cardClasses} rounded-lg w-2/3 border border-[var(--luxury-gold)]/10`} />
          </div>
        </div>
      </div>
    );
  }

  if (error || !room) {
    return (
      <div 
        className={`min-h-screen ${bgClasses} w-screen relative -mt-6 -mb-6`}
        style={{ 
          marginLeft: 'calc(50% - 50vw)',
          marginRight: 'calc(50% - 50vw)',
          width: '100vw',
          paddingTop: '1.5rem',
          paddingBottom: '1.5rem',
          zIndex: 1
        }}
      >
        <div className="w-full px-2 sm:px-4 md:px-6 lg:px-8 py-8 sm:py-12">
          <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"
          >
            <p className="text-red-300 font-light text-lg mb-6 tracking-wide">
              {error || 'Room not found'}
            </p>
            <button
              onClick={() => navigate('/rooms')}
              className="inline-flex items-center gap-2 bg-gradient-to-r 
                from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] text-[#0f0f0f] 
                px-6 py-3 rounded-sm hover:from-[var(--luxury-gold-light)] 
                hover:to-[var(--luxury-gold)] transition-all duration-300 
                font-medium tracking-wide shadow-lg shadow-[var(--luxury-gold)]/30"
            >
              <ArrowLeft className="w-5 h-5" />
              Back to Room List
            </button>
          </div>
        </div>
      </div>
    );
  }

  const roomType = room.room_type;
  const formattedPrice = formatCurrency(room?.price || roomType?.base_price || 0);

  return (
    <div 
      className={`min-h-screen ${bgClasses} w-screen relative -mt-6 -mb-6`}
      style={{ 
        marginLeft: 'calc(50% - 50vw)',
        marginRight: 'calc(50% - 50vw)',
        width: '100vw',
        paddingTop: '1.5rem',
        paddingBottom: '1.5rem',
        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"
          className="inline-flex items-center gap-1 
            text-[var(--luxury-gold)]/80 hover:text-[var(--luxury-gold)] 
            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 list</span>
        </Link>

        {}
        <div className="mb-4">
          <RoomGallery
            images={(room.images && room.images.length > 0) 
              ? room.images 
              : (roomType?.images || [])}
            roomName={roomType?.name || 'Room'}
          />
        </div>

        {}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-3 sm:gap-4 lg:gap-6 mb-4 sm:mb-5">
          {}
          <div className="lg:col-span-8 space-y-3 sm:space-y-4">
            {}
            <div className="space-y-3">
              {}
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-1.5 mb-2">
                    {room.featured && (
                      <div className="flex items-center gap-1 
                        bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] 
                        text-[#0f0f0f] px-2 py-0.5 rounded-sm 
                        text-[10px] sm:text-xs font-medium tracking-wide
                        shadow-sm shadow-[var(--luxury-gold)]/30"
                      >
                        <Sparkles className="w-2.5 h-2.5" />
                        Featured
                      </div>
                    )}
                    <div className="flex flex-col gap-1">
                      <div
                        className={`px-2 py-0.5 rounded-sm 
                          text-[10px] sm:text-xs font-medium tracking-wide
                          backdrop-blur-sm shadow-sm
                          ${
                            room.status === 'available'
                              ? 'bg-green-500/90 text-white border border-green-400/50'
                              : room.status === 'occupied'
                              ? 'bg-red-500/90 text-white border border-red-400/50'
                              : 'bg-gray-500/90 text-white border border-gray-400/50'
                          }`}
                      >
                        {room.status === 'available'
                          ? 'Available Now'
                          : room.status === 'occupied'
                          ? 'Booked'
                          : 'Maintenance'}
                      </div>
                      {room.status === 'occupied' && bookedUntilDate && (
                        <p className={`text-[9px] sm:text-[10px] ${textClasses.secondary} font-light leading-tight`}>
                          Booked until {bookedUntilDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                        </p>
                      )}
                      {room.status === 'occupied' && nextAvailableDate && (
                        <p className="text-[9px] sm:text-[10px] text-[var(--luxury-gold)] font-light leading-tight">
                          Available from {nextAvailableDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                        </p>
                      )}
                    </div>
                  </div>
                  
                  <h1 className={`text-xl sm:text-2xl lg:text-3xl font-serif font-semibold 
                    ${textClasses.primary} mb-2 tracking-tight leading-tight
                    ${theme.theme_layout_mode === 'light' 
                      ? 'bg-gradient-to-r from-gray-900 via-[var(--luxury-gold)] to-gray-900' 
                      : 'bg-gradient-to-r from-white via-[var(--luxury-gold)] to-white'} 
                    bg-clip-text text-transparent`}
              >
                {roomType?.name}
              </h1>
                </div>
              </div>
              
              {}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-2 sm:gap-3 mb-3">
                <div className={`flex items-center gap-2 
                  p-2 ${cardClasses} 
                  rounded-lg border border-[var(--luxury-gold)]/20 
                  hover:border-[var(--luxury-gold)]/40 transition-all duration-300`}
              >
                  <div className="p-1 bg-[var(--luxury-gold)]/10 rounded-lg 
                    border border-[var(--luxury-gold)]/30">
                    <MapPin className="w-3.5 h-3.5 text-[var(--luxury-gold)]" />
                  </div>
                  <div>
                    <p className={`text-[10px] sm:text-xs ${textClasses.muted} font-light tracking-wide mb-0.5`}>
                      Location
                    </p>
                    <p className={`text-xs sm:text-sm ${textClasses.primary} font-light tracking-wide`}>
                    Room {room.room_number} - Floor {room.floor}
                    </p>
                  </div>
                </div>
                
                <div className={`flex items-center gap-2 
                  p-2 ${cardClasses} 
                  rounded-lg border border-[var(--luxury-gold)]/20`}
                >
                  <div className="p-1 bg-[var(--luxury-gold)]/10 rounded-lg 
                    border border-[var(--luxury-gold)]/30">
                    <Users className="w-3.5 h-3.5 text-[var(--luxury-gold)]" />
                  </div>
                  <div>
                    <p className={`text-[10px] sm:text-xs ${textClasses.muted} font-light tracking-wide mb-0.5`}>
                      Capacity
                    </p>
                    <p className={`text-xs sm:text-sm ${textClasses.primary} font-light tracking-wide`}>
                    {room?.capacity || roomType?.capacity || 0} guests
                    </p>
                  </div>
                </div>

                {room.average_rating != null && (
                  <div className={`flex items-center gap-2 
                    p-2 ${cardClasses} 
                    rounded-lg border border-[var(--luxury-gold)]/20 
                    hover:border-[var(--luxury-gold)]/40 transition-all duration-300`}
                  >
                    <div className="p-1 bg-[var(--luxury-gold)]/10 rounded-lg 
                      border border-[var(--luxury-gold)]/30">
                      <Star className="w-3.5 h-3.5 text-[var(--luxury-gold)] fill-[var(--luxury-gold)]" />
                    </div>
                    <div>
                      <p className={`text-[10px] sm:text-xs ${textClasses.muted} font-light tracking-wide mb-0.5`}>
                        Rating
                      </p>
                  <div className="flex items-center gap-1">
                        <p className={`text-xs sm:text-sm ${textClasses.primary} font-semibold`}>
                          {Number(room.average_rating).toFixed(1)}
                        </p>
                        <span className={`text-[10px] sm:text-xs ${textClasses.muted} font-light`}>
                          ({room.total_reviews || 0})
                    </span>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {}
            {(room?.description || roomType?.description) && (
              <div className={`p-3 sm:p-4 ${cardClasses} 
                rounded-lg border border-[var(--luxury-gold)]/20 
                backdrop-blur-xl shadow-lg shadow-[var(--luxury-gold)]/5`}
              >
                <div className="flex items-center gap-2 mb-2">
                  <div className="p-1 bg-[var(--luxury-gold)]/10 rounded-lg 
                    border border-[var(--luxury-gold)]/30">
                    <Award className="w-3.5 h-3.5 text-[var(--luxury-gold)]" />
                  </div>
                  <h2 className={`text-sm sm:text-base font-serif font-semibold 
                    ${textClasses.primary} tracking-wide`}
                >
                  {room?.description ? 'Room Description' : 'Room Type Description'}
                </h2>
                </div>
                <p className={`${textClasses.secondary} leading-relaxed 
                  font-light tracking-wide text-xs sm:text-sm`}
                >
                  {room?.description || roomType?.description}
                </p>
              </div>
            )}

            {}
            <div className={`p-3 sm:p-4 ${cardClasses} 
              rounded-lg border border-[var(--luxury-gold)]/20 
              backdrop-blur-xl shadow-lg shadow-[var(--luxury-gold)]/5`}
            >
              <div className="flex items-center gap-2 mb-2">
                <div className="p-1 bg-[var(--luxury-gold)]/10 rounded-lg 
                  border border-[var(--luxury-gold)]/30">
                  <Sparkles className="w-3.5 h-3.5 text-[var(--luxury-gold)]" />
                </div>
                <h2 className={`text-sm sm:text-base font-serif font-semibold 
                  ${textClasses.primary} tracking-wide`}
              >
                  Amenities & Features
              </h2>
              </div>
              <RoomAmenities
                amenities={
                  (room.amenities && room.amenities.length > 0)
                    ? room.amenities
                    : (roomType?.amenities || [])
                }
              />
              <div className="mt-6 pt-6 border-t border-[var(--luxury-gold)]/20">
                <Link
                  to="/services"
                  className="inline-flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-[var(--luxury-gold)]/20 to-[var(--luxury-gold-dark)]/10 hover:from-[var(--luxury-gold)]/30 hover:to-[var(--luxury-gold)]/20 text-[var(--luxury-gold)] rounded-lg font-medium transition-all duration-300 border border-[var(--luxury-gold)]/30 hover:border-[var(--luxury-gold)]/50"
                >
                  <Award className="w-4 h-4" />
                  <span className="text-sm">View All Services</span>
                </Link>
              </div>
            </div>
          </div>

          {}
          <aside className="lg:col-span-4">
            <div className={`${cardClasses} 
              rounded-lg border border-[var(--luxury-gold)]/30 
              backdrop-blur-xl shadow-lg shadow-[var(--luxury-gold)]/20 
              p-3 sm:p-4 sticky top-4`}
            >
              {}
              <div className="mb-4 pb-4 border-b border-[var(--luxury-gold)]/20">
                <p className={`text-[10px] sm:text-xs ${textClasses.muted} font-light tracking-wide mb-1`}>
                  Starting from
                </p>
                <div className="flex items-baseline gap-1.5">
                  <CurrencyIcon className="text-[var(--luxury-gold)]" size={16} />
                <div>
                    <div className="text-2xl sm:text-3xl font-serif font-semibold 
                      bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-light)] 
                      bg-clip-text text-transparent tracking-tight"
                    >
                    {formattedPrice}
                    </div>
                    <div className={`text-[10px] sm:text-xs ${textClasses.muted} font-light tracking-wide mt-0.5`}>
                      / night
                    </div>
                  </div>
                </div>
              </div>

              {}
              {userInfo?.role !== 'admin' && userInfo?.role !== 'staff' && (
                <>
                  <div className="mb-3">
                    <button
                      onClick={() => {
                        if (room.status !== 'available') {
                          toast.error('This room is not available for booking');
                          return;
                        }
                        if (!isAuthenticated) {
                          toast.error('Please login to make a booking');
                          openModal('login');
                          return;
                        }
                        setShowBookingModal(true);
                      }}
                      disabled={room.status !== 'available'}
                      className={`block w-full py-2 text-center 
                        font-medium rounded-sm transition-all duration-300 
                        tracking-wide relative overflow-hidden group text-xs sm:text-sm
                        ${
                        room.status === 'available'
                            ? 'bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] text-[#0f0f0f] hover:from-[var(--luxury-gold-light)] hover:to-[var(--luxury-gold)] shadow-sm shadow-[var(--luxury-gold)]/30 hover:shadow-[var(--luxury-gold)]/50'
                            : 'bg-gray-800 text-gray-500 cursor-not-allowed border border-gray-700'
                      }`}
                    >
                      <span className="relative z-10 flex items-center justify-center gap-1.5">
                        <Calendar className="w-3.5 h-3.5" />
                      {room.status === 'available' ? 'Book Now' : 'Not Available'}
                      </span>
                      {room.status === 'available' && (
                        <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>

                  {room.status === 'available' && (
                    <div className="flex items-start gap-2 p-2 bg-[var(--luxury-gold)]/5 
                      rounded-lg border border-[var(--luxury-gold)]/20 mb-3"
                    >
                      <Shield className="w-3.5 h-3.5 text-[var(--luxury-gold)] mt-0.5 flex-shrink-0" />
                      <p className={`text-[10px] sm:text-xs ${textClasses.secondary} font-light tracking-wide leading-relaxed`}>
                        <strong className="text-[var(--luxury-gold)]">20% deposit required</strong> to secure your booking. Pay the remaining balance on arrival at the hotel.
                    </p>
                    </div>
                  )}
                </>
              )}

              {}
              <div className="space-y-2">
                <div className="flex items-center justify-between 
                  py-1.5 border-b border-[var(--luxury-gold)]/10"
                >
                  <span className={`text-[10px] sm:text-xs ${textClasses.muted} font-light tracking-wide`}>Room Type</span>
                  <strong className={`text-xs sm:text-sm ${textClasses.primary} font-light`}>{roomType?.name}</strong>
                </div>
                <div className="flex items-center justify-between 
                  py-1.5 border-b border-[var(--luxury-gold)]/10"
                >
                  <span className={`text-[10px] sm:text-xs ${textClasses.muted} font-light tracking-wide`}>Max Guests</span>
                  <span className={`text-xs sm:text-sm ${textClasses.primary} font-light`}>{(room?.capacity || roomType?.capacity || 0)} guests</span>
                </div>
                {room?.room_size && (
                  <div className="flex items-center justify-between 
                    py-1.5 border-b border-[var(--luxury-gold)]/10"
                  >
                    <span className={`text-[10px] sm:text-xs ${textClasses.muted} font-light tracking-wide`}>Room Size</span>
                    <span className={`text-xs sm:text-sm ${textClasses.primary} font-light`}>{room.room_size}</span>
                  </div>
                )}
                {room?.view && (
                  <div className={`flex items-center justify-between ${room?.room_size ? 'py-1.5 border-b border-[var(--luxury-gold)]/10' : 'py-1.5'}`}>
                    <span className={`text-[10px] sm:text-xs ${textClasses.muted} font-light tracking-wide`}>View</span>
                    <span className={`text-xs sm:text-sm ${textClasses.primary} font-light`}>{room.view}</span>
                  </div>
                )}
              </div>
            </div>
          </aside>
        </div>

        {}
        <div className={`mb-4 p-3 sm:p-4 ${cardClasses} 
          rounded-lg border border-[var(--luxury-gold)]/20 
          backdrop-blur-xl shadow-lg shadow-[var(--luxury-gold)]/5`}
        >
          <ReviewSection roomId={room.id} />
        </div>
      </div>

      {/* Booking Modal */}
      {room && (
        <LuxuryBookingModal
          roomId={room.id}
          isOpen={showBookingModal}
          onClose={() => setShowBookingModal(false)}
          onSuccess={(bookingId) => {
            setShowBookingModal(false);
            navigate(`/booking-success/${bookingId}`);
          }}
        />
      )}
    </div>
  );
};

export default RoomDetailPage;
