import React, { useState, useEffect, useMemo } from 'react';
import {
  Hotel,
  Wrench,
  Sparkles,
  ClipboardCheck,
  Filter,
  RefreshCw,
  CheckCircle,
  AlertTriangle,
  Users,
  ChevronDown,
  ChevronUp,
  Calendar,
  MapPin,
  ArrowRight,
  Search,
  X,
  ArrowUpRight,
} from 'lucide-react';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import { logger } from '../../shared/utils/logger';
import advancedRoomService, {
  RoomStatusBoardItem,
  OptimalRoomAssignmentRequest,
} from '../../features/rooms/services/advancedRoomService';
import roomService from '../../features/rooms/services/roomService';
import bookingService, { Booking } from '../../features/bookings/services/bookingService';
import MaintenanceManagement from '../../features/hotel_services/components/MaintenanceManagement';
import HousekeepingManagement from '../../features/hotel_services/components/HousekeepingManagement';
import InspectionManagement from '../../features/hotel_services/components/InspectionManagement';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';

type Tab = 'status-board' | 'room-assignment' | 'maintenance' | 'housekeeping' | 'inspections';

const AdvancedRoomManagementPage: React.FC = () => {
  const { formatCurrency: _formatCurrency } = useFormatCurrency();
  const [activeTab, setActiveTab] = useState<Tab>('status-board');
  const [loading, setLoading] = useState(true);
  const [rooms, setRooms] = useState<RoomStatusBoardItem[]>([]);
  const [selectedFloor, setSelectedFloor] = useState<number | null>(null);
  const [floors, setFloors] = useState<number[]>([]);
  const [expandedRooms, setExpandedRooms] = useState<Set<number>>(new Set());

  // Room assignment state
  const [assigningRoom, setAssigningRoom] = useState(false);
  const [selectedBooking, setSelectedBooking] = useState<Booking | null>(null);
  const [bookingSearch, setBookingSearch] = useState('');
  const [bookingSearchResults, setBookingSearchResults] = useState<Booking[]>([]);
  const [searchingBookings, setSearchingBookings] = useState(false);
  const [availableRoomsForAssignment, setAvailableRoomsForAssignment] = useState<RoomStatusBoardItem[]>([]);
  const [loadingAvailableRooms, setLoadingAvailableRooms] = useState(false);
  const [showUpgradeSuggestions, setShowUpgradeSuggestions] = useState(false);
  const [upgradeSuggestions, setUpgradeSuggestions] = useState<RoomStatusBoardItem[]>([]);

  useEffect(() => {
    fetchRoomStatusBoard();
    fetchFloors();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedFloor]);

  const fetchRoomStatusBoard = async () => {
    try {
      setLoading(true);
      const response = await advancedRoomService.getRoomStatusBoard(selectedFloor || undefined);
      if (response.status === 'success') {
        setRooms(response.data.rooms);
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to fetch room status board');
    } finally {
      setLoading(false);
    }
  };

  const fetchFloors = async () => {
    try {
      const response = await roomService.getRooms({ limit: 1000, page: 1 });
      if (response.data?.rooms) {
        const uniqueFloors = Array.from(
          new Set(response.data.rooms.map((r: { floor?: number | null }) => r.floor).filter((f: number | null | undefined): f is number => f != null))
        ).sort((a: number, b: number) => a - b) as number[];
        setFloors(uniqueFloors);
      }
    } catch (error) {
      logger.error('Failed to fetch floors', error);
    }
  };

  const toggleRoomExpansion = (roomId: number) => {
    const newExpanded = new Set(expandedRooms);
    if (newExpanded.has(roomId)) {
      newExpanded.delete(roomId);
    } else {
      newExpanded.add(roomId);
    }
    setExpandedRooms(newExpanded);
  };

  // Group rooms by floor
  const roomsByFloor = useMemo(() => {
    const grouped: Record<number, RoomStatusBoardItem[]> = {};
    rooms.forEach(room => {
      if (!grouped[room.floor]) {
        grouped[room.floor] = [];
      }
      grouped[room.floor].push(room);
    });
    return grouped;
  }, [rooms]);

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'available':
        return {
          bg: 'bg-gradient-to-br from-emerald-50 via-green-50 to-emerald-100',
          border: 'border-emerald-300/50',
          text: 'text-emerald-800',
          badge: 'bg-gradient-to-r from-emerald-500 to-green-600 text-white',
          shadow: 'shadow-emerald-200/50'
        };
      case 'occupied':
        return {
          bg: 'bg-gradient-to-br from-blue-50 via-indigo-50 to-blue-100',
          border: 'border-blue-300/50',
          text: 'text-blue-800',
          badge: 'bg-gradient-to-r from-blue-500 to-indigo-600 text-white',
          shadow: 'shadow-blue-200/50'
        };
      case 'maintenance':
        return {
          bg: 'bg-gradient-to-br from-red-50 via-rose-50 to-red-100',
          border: 'border-red-300/50',
          text: 'text-red-800',
          badge: 'bg-gradient-to-r from-red-500 to-rose-600 text-white',
          shadow: 'shadow-red-200/50'
        };
      case 'cleaning':
        return {
          bg: 'bg-gradient-to-br from-amber-50 via-yellow-50 to-amber-100',
          border: 'border-amber-300/50',
          text: 'text-amber-800',
          badge: 'bg-gradient-to-r from-amber-500 to-yellow-600 text-white',
          shadow: 'shadow-amber-200/50'
        };
      default:
        return {
          bg: 'bg-gradient-to-br from-gray-50 via-slate-50 to-gray-100',
          border: 'border-gray-300/50',
          text: 'text-gray-800',
          badge: 'bg-gradient-to-r from-gray-500 to-slate-600 text-white',
          shadow: 'shadow-gray-200/50'
        };
    }
  };

  const getStatusIcon = (status: string) => {
    const iconClass = "w-5 h-5";
    switch (status) {
      case 'available':
        return <CheckCircle className={iconClass} />;
      case 'occupied':
        return <Users className={iconClass} />;
      case 'maintenance':
        return <Wrench className={iconClass} />;
      case 'cleaning':
        return <Sparkles className={iconClass} />;
      default:
        return <AlertTriangle className={iconClass} />;
    }
  };

  const getStatusLabel = (status: string) => {
    switch (status) {
      case 'available':
        return 'Available';
      case 'occupied':
        return 'Occupied';
      case 'maintenance':
        return 'Maintenance';
      case 'cleaning':
        return 'Cleaning';
      default:
        return 'Unknown';
    }
  };

  // Room assignment handlers
  const handleSearchBookings = async () => {
    if (!bookingSearch.trim()) {
      setBookingSearchResults([]);
      return;
    }

    try {
      setSearchingBookings(true);
      const response = await bookingService.getAllBookings({
        search: bookingSearch,
        status: 'confirmed',
        limit: 10,
      });
      setBookingSearchResults(response.data.bookings || []);
    } catch (error: unknown) {
      toast.error('Failed to search bookings');
      logger.error('Error searching bookings', error);
    } finally {
      setSearchingBookings(false);
    }
  };

  useEffect(() => {
    const timeoutId = setTimeout(() => {
      if (bookingSearch.trim()) {
        handleSearchBookings();
      } else {
        setBookingSearchResults([]);
      }
    }, 300);

    return () => clearTimeout(timeoutId);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [bookingSearch]);

  const handleSelectBooking = async (booking: Booking) => {
    setSelectedBooking(booking);
    setBookingSearch('');
    setBookingSearchResults([]);
    
    // Fetch available rooms for the booking dates
    try {
      setLoadingAvailableRooms(true);
      const _response = await roomService.searchAvailableRooms({
        from: booking.check_in_date,
        to: booking.check_out_date,
        limit: 100,
      });
      
      // Get room status board to match with available rooms
      const statusBoardResponse = await advancedRoomService.getRoomStatusBoard();
      const allRooms = statusBoardResponse.data.rooms || [];
      
      // Filter to show only available rooms that match the booking's room type or better
      const availableRooms = allRooms.filter(room => {
        const isAvailable = room.status === 'available';
        const matchesType = !booking.room?.room_type || 
          room.room_type === booking.room.room_type.name ||
          (room.room_type && booking.room.room_type);
        return isAvailable && matchesType;
      });
      
      setAvailableRoomsForAssignment(availableRooms);
      
      // Get upgrade suggestions (better room types)
      const upgradeRooms = allRooms.filter(room => {
        return room.status === 'available' && 
               room.room_type && 
               room.room_type !== booking.room?.room_type?.name;
      });
      setUpgradeSuggestions(upgradeRooms.slice(0, 5));
      
    } catch (error: unknown) {
      toast.error('Failed to load available rooms');
      logger.error('Error loading available rooms', error);
    } finally {
      setLoadingAvailableRooms(false);
    }
  };

  const handleAssignRoom = async (roomId: number, roomNumber: string) => {
    if (!selectedBooking) return;

    try {
      setAssigningRoom(true);
      await bookingService.updateBooking(selectedBooking.id, {
        room_id: roomId,
      });
      
      toast.success(`Room ${roomNumber} assigned successfully!`);
      setSelectedBooking(null);
      setAvailableRoomsForAssignment([]);
      setUpgradeSuggestions([]);
      fetchRoomStatusBoard();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to assign room');
      logger.error('Error assigning room', error);
    } finally {
      setAssigningRoom(false);
    }
  };

  const handleGetOptimalRoom = async () => {
    if (!selectedBooking) return;

    try {
      setLoadingAvailableRooms(true);
      const request: OptimalRoomAssignmentRequest = {
        room_type_id: selectedBooking.room?.room_type?.id || 0,
        check_in: selectedBooking.check_in_date,
        check_out: selectedBooking.check_out_date,
        num_guests: selectedBooking.guest_count || 1,
      };

      const response = await advancedRoomService.assignOptimalRoom(request);
      if (response.status === 'success' && response.data?.recommended_room) {
        const recommendedRoom = response.data.recommended_room;
        toast.success(`Optimal room suggestion: Room ${recommendedRoom.room_number}`);
        // Auto-select the recommended room
        handleAssignRoom(recommendedRoom.id, recommendedRoom.room_number);
      }
    } catch (error: unknown) {
      toast.error('Failed to get optimal room suggestion');
      logger.error('Error getting optimal room', error);
    } finally {
      setLoadingAvailableRooms(false);
    }
  };

  if (loading && rooms.length === 0) {
    return <Loading />;
  }

  return (
    <div className="p-6 max-w-7xl mx-auto">
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-gray-900 mb-2">Advanced Room Management</h1>
        <p className="text-gray-600">Manage room status, maintenance, housekeeping, and inspections</p>
      </div>

      {/* Tabs */}
      <div className="mb-6 border-b border-gray-200">
        <nav className="-mb-px flex space-x-8">
          {[
            { id: 'status-board' as Tab, label: 'Room Status Board', icon: Hotel },
            { id: 'room-assignment' as Tab, label: 'Room Assignment', icon: ArrowRight },
            { id: 'maintenance' as Tab, label: 'Maintenance', icon: Wrench },
            { id: 'housekeeping' as Tab, label: 'Housekeeping', icon: Sparkles },
            { id: 'inspections' as Tab, label: 'Inspections', icon: ClipboardCheck },
          ].map((tab) => {
            const Icon = tab.icon;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`
                  flex items-center space-x-2 py-4 px-1 border-b-2 font-medium text-sm
                  ${
                    activeTab === tab.id
                      ? 'border-blue-500 text-blue-600'
                      : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                  }
                `}
              >
                <Icon className="w-5 h-5" />
                <span>{tab.label}</span>
              </button>
            );
          })}
        </nav>
      </div>

      {/* Status Board Tab */}
      {activeTab === 'status-board' && (
        <div className="space-y-8">
          {/* Header Controls */}
          <div className="flex items-center justify-between bg-gradient-to-r from-slate-50 to-gray-50 rounded-xl p-4 border border-slate-200/50 shadow-sm">
            <div className="flex items-center space-x-4">
              <div className="flex items-center space-x-3 bg-white rounded-lg px-4 py-2 shadow-sm border border-slate-200">
                <Filter className="w-5 h-5 text-slate-600" />
                <select
                  value={selectedFloor || ''}
                  onChange={(e) => setSelectedFloor(e.target.value ? parseInt(e.target.value) : null)}
                  className="border-0 bg-transparent text-sm font-medium text-slate-700 focus:outline-none focus:ring-0 cursor-pointer"
                >
                  <option value="">All Floors</option>
                  {floors.map((floor) => (
                    <option key={floor} value={floor}>
                      Floor {floor}
                    </option>
                  ))}
                </select>
              </div>
              <div className="text-sm text-slate-600">
                <span className="font-semibold text-slate-900">{rooms.length}</span> rooms
              </div>
            </div>
            <button
              onClick={fetchRoomStatusBoard}
              className="flex items-center space-x-2 px-5 py-2.5 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-lg hover:from-blue-700 hover:to-indigo-700 transition-all duration-200 shadow-md hover:shadow-lg font-medium"
            >
              <RefreshCw className="w-4 h-4" />
              <span>Refresh</span>
            </button>
          </div>

          {/* Floors Display */}
          {Object.keys(roomsByFloor).length === 0 ? (
            <div className="text-center py-16 bg-gradient-to-br from-slate-50 to-gray-50 rounded-2xl border border-slate-200">
              <Hotel className="w-20 h-20 text-slate-300 mx-auto mb-4" />
              <p className="text-slate-500 text-lg font-medium">No rooms found</p>
            </div>
          ) : (
            <div className="space-y-8">
              {Object.entries(roomsByFloor)
                .sort(([a], [b]) => parseInt(b) - parseInt(a))
                .map(([floor, floorRooms]) => (
                  <div key={floor} className="space-y-4">
                    {/* Floor Header */}
                    <div className="flex items-center space-x-4">
                      <div className="flex items-center space-x-3">
                        <div className="w-1 h-12 bg-gradient-to-b from-blue-600 to-indigo-600 rounded-full"></div>
                        <div>
                          <h2 className="text-2xl font-bold text-slate-900 flex items-center space-x-2">
                            <MapPin className="w-6 h-6 text-blue-600" />
                            <span>Floor {floor}</span>
                          </h2>
                          <p className="text-sm text-slate-500 mt-0.5">
                            {floorRooms.length} {floorRooms.length === 1 ? 'room' : 'rooms'}
                          </p>
                        </div>
                      </div>
                      <div className="flex-1 h-px bg-gradient-to-r from-slate-200 via-slate-300 to-transparent"></div>
                    </div>

                    {/* Rooms Grid */}
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-4">
                      {floorRooms.map((room) => {
                        const statusColors = getStatusColor(room.status);
                        return (
                          <div
                            key={room.id}
                            className={`
                              group relative overflow-hidden rounded-xl border-2 transition-all duration-300
                              ${statusColors.bg} ${statusColors.border}
                              hover:shadow-xl hover:scale-[1.02] cursor-pointer
                              ${expandedRooms.has(room.id) ? 'shadow-lg' : 'shadow-md'}
                            `}
                            onClick={() => toggleRoomExpansion(room.id)}
                          >
                            {/* Status Badge */}
                            <div className={`absolute top-3 right-3 px-3 py-1 rounded-full text-xs font-semibold shadow-lg ${statusColors.badge} flex items-center space-x-1.5`}>
                              {getStatusIcon(room.status)}
                              <span>{getStatusLabel(room.status)}</span>
                            </div>

                            {/* Room Content */}
                            <div className="p-5 pt-4">
                              <div className="mb-4">
                                <div className="flex items-center space-x-2 mb-2">
                                  <h3 className="text-2xl font-bold text-slate-900 font-mono">{room.room_number}</h3>
                                  {room.room_type && (
                                    <span className="text-xs font-medium text-slate-600 bg-white/60 px-2 py-1 rounded">
                                      {room.room_type}
                                    </span>
                                  )}
                                </div>
                              </div>

                              {/* Expanded Details */}
                              {expandedRooms.has(room.id) && (
                                <div className="mt-4 pt-4 border-t border-slate-300/30 space-y-3 animate-in fade-in slide-in-from-top-2 duration-200">
                                  {room.current_booking && (
                                    <div className="bg-white/60 rounded-lg p-3 space-y-2">
                                      <div className="flex items-center space-x-2 text-sm font-semibold text-slate-700">
                                        <Users className="w-4 h-4" />
                                        <span>Guest</span>
                                      </div>
                                      <p className="text-sm font-medium text-slate-900">{room.current_booking.guest_name}</p>
                                      <div className="flex items-center space-x-1 text-xs text-slate-600">
                                        <Calendar className="w-3 h-3" />
                                        <span>Check-out: {new Date(room.current_booking.check_out).toLocaleDateString()}</span>
                                      </div>
                                    </div>
                                  )}

                                  {room.active_maintenance && (
                                    <div className="bg-red-50/80 rounded-lg p-3 space-y-2 border border-red-200/50">
                                      <div className="flex items-center space-x-2 text-sm font-semibold text-red-800">
                                        <Wrench className="w-4 h-4" />
                                        <span>Maintenance</span>
                                      </div>
                                      <p className="text-sm font-medium text-red-900">{room.active_maintenance.title}</p>
                                      <p className="text-xs text-red-700 capitalize">{room.active_maintenance.type}</p>
                                    </div>
                                  )}

                                  {room.pending_housekeeping_count > 0 && (
                                    <div className="bg-amber-50/80 rounded-lg p-3 space-y-2 border border-amber-200/50">
                                      <div className="flex items-center space-x-2 text-sm font-semibold text-amber-800">
                                        <Sparkles className="w-4 h-4" />
                                        <span>Housekeeping</span>
                                      </div>
                                      <p className="text-sm font-medium text-amber-900">
                                        {room.pending_housekeeping_count} pending {room.pending_housekeeping_count === 1 ? 'task' : 'tasks'}
                                      </p>
                                    </div>
                                  )}

                                  {!room.current_booking && !room.active_maintenance && room.pending_housekeeping_count === 0 && (
                                    <div className="text-center py-3">
                                      <CheckCircle className="w-8 h-8 text-emerald-500 mx-auto mb-2" />
                                      <p className="text-sm text-slate-600 font-medium">All Clear</p>
                                    </div>
                                  )}
                                </div>
                              )}

                              {/* Collapse Indicator */}
                              <div className="mt-4 flex justify-center">
                                {expandedRooms.has(room.id) ? (
                                  <ChevronUp className="w-5 h-5 text-slate-500 group-hover:text-slate-700 transition-colors" />
                                ) : (
                                  <ChevronDown className="w-5 h-5 text-slate-500 group-hover:text-slate-700 transition-colors" />
                                )}
                              </div>
                            </div>

                            {/* Decorative Corner */}
                            <div className={`absolute bottom-0 right-0 w-20 h-20 ${statusColors.bg} opacity-10 rounded-tl-full`}></div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                ))}
            </div>
          )}
        </div>
      )}

      {/* Room Assignment Tab */}
      {activeTab === 'room-assignment' && (
        <div className="space-y-8">
          <div className="bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <div className="p-2.5 rounded-xl bg-gradient-to-br from-indigo-500/10 to-purple-500/10 border border-indigo-200/40">
                  <ArrowRight className="w-6 h-6 text-indigo-600" />
                </div>
                <h2 className="text-3xl font-extrabold text-gray-900">Room Assignment</h2>
              </div>
              <p className="text-gray-600 text-base max-w-2xl leading-relaxed">
                Assign or change rooms for bookings with visual room selection
              </p>
            </div>
          </div>

          {/* Booking Selection */}
          <div className="bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
            <h3 className="text-xl font-bold text-gray-900 mb-6 flex items-center gap-3">
              <div className="w-8 h-8 rounded-lg bg-indigo-100 flex items-center justify-center">
                <span className="text-indigo-600 font-bold">1</span>
              </div>
              Select Booking
            </h3>
            
            {!selectedBooking ? (
              <div className="space-y-4">
                <div className="relative">
                  <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                  <input
                    type="text"
                    value={bookingSearch}
                    onChange={(e) => setBookingSearch(e.target.value)}
                    placeholder="Search by booking number, guest name, or email..."
                    className="w-full pl-12 pr-4 py-3.5 bg-white border-2 border-gray-200 rounded-xl focus:border-indigo-400 focus:ring-4 focus:ring-indigo-100 transition-all duration-200 text-gray-700"
                  />
                </div>

                {bookingSearchResults.length > 0 && (
                  <div className="border-2 border-gray-200 rounded-xl overflow-hidden max-h-96 overflow-y-auto">
                    {bookingSearchResults.map((booking) => (
                      <div
                        key={booking.id}
                        onClick={() => handleSelectBooking(booking)}
                        className="p-4 hover:bg-indigo-50 cursor-pointer border-b border-gray-100 last:border-b-0 transition-colors"
                      >
                        <div className="flex items-center justify-between">
                          <div>
                            <div className="font-bold text-gray-900">{booking.booking_number}</div>
                            <div className="text-sm text-gray-600">
                              {booking.guest_info?.full_name || booking.user?.name}
                            </div>
                            <div className="text-xs text-gray-500 mt-1">
                              {new Date(booking.check_in_date).toLocaleDateString()} - {new Date(booking.check_out_date).toLocaleDateString()}
                            </div>
                          </div>
                          <div className="text-right">
                            <div className="text-sm font-semibold text-gray-900">
                              Room {booking.room?.room_number || 'N/A'}
                            </div>
                            <div className="text-xs text-gray-500">{booking.room?.room_type?.name}</div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}

                {searchingBookings && (
                  <div className="text-center py-8">
                    <RefreshCw className="w-8 h-8 text-indigo-600 animate-spin mx-auto mb-2" />
                    <p className="text-gray-600">Searching bookings...</p>
                  </div>
                )}
              </div>
            ) : (
              <div className="bg-indigo-50 rounded-xl p-6 border-2 border-indigo-200">
                <div className="flex items-center justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-2">
                      <h4 className="text-lg font-bold text-gray-900">{selectedBooking.booking_number}</h4>
                      <span className="px-2 py-1 bg-indigo-600 text-white text-xs font-semibold rounded">
                        {selectedBooking.status}
                      </span>
                    </div>
                    <div className="text-sm text-gray-700 space-y-1">
                      <div><strong>Guest:</strong> {selectedBooking.guest_info?.full_name || selectedBooking.user?.name}</div>
                      <div><strong>Current Room:</strong> Room {selectedBooking.room?.room_number || 'N/A'} - {selectedBooking.room?.room_type?.name}</div>
                      <div><strong>Dates:</strong> {new Date(selectedBooking.check_in_date).toLocaleDateString()} to {new Date(selectedBooking.check_out_date).toLocaleDateString()}</div>
                      <div><strong>Guests:</strong> {selectedBooking.guest_count || 1}</div>
                    </div>
                  </div>
                  <button
                    onClick={() => {
                      setSelectedBooking(null);
                      setAvailableRoomsForAssignment([]);
                      setUpgradeSuggestions([]);
                    }}
                    className="p-2 text-gray-400 hover:text-gray-600 hover:bg-white rounded-lg transition-colors"
                  >
                    <X className="w-5 h-5" />
                  </button>
                </div>
              </div>
            )}
          </div>

          {/* Room Selection */}
          {selectedBooking && (
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <h3 className="text-xl font-bold text-gray-900 flex items-center gap-3">
                  <div className="w-8 h-8 rounded-lg bg-indigo-100 flex items-center justify-center">
                    <span className="text-indigo-600 font-bold">2</span>
                  </div>
                  Select New Room
                </h3>
                <button
                  onClick={handleGetOptimalRoom}
                  disabled={loadingAvailableRooms}
                  className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-indigo-500 to-purple-600 text-white rounded-lg hover:from-indigo-600 hover:to-purple-700 font-medium disabled:opacity-50 transition-all"
                >
                  <ArrowUpRight className="w-4 h-4" />
                  Get Optimal Room
                </button>
              </div>

              {loadingAvailableRooms ? (
                <div className="text-center py-12 bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50">
                  <RefreshCw className="w-8 h-8 text-indigo-600 animate-spin mx-auto mb-2" />
                  <p className="text-gray-600">Loading available rooms...</p>
                </div>
              ) : availableRoomsForAssignment.length === 0 ? (
                <div className="text-center py-12 bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50">
                  <Hotel className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                  <p className="text-gray-600">No available rooms found for selected dates</p>
                </div>
              ) : (
                <>
                  {showUpgradeSuggestions && upgradeSuggestions.length > 0 && (
                    <div className="bg-gradient-to-r from-amber-50 to-yellow-50 rounded-xl p-6 border-2 border-amber-200">
                      <h4 className="font-bold text-amber-900 mb-4 flex items-center gap-2">
                        <ArrowUpRight className="w-5 h-5" />
                        Upgrade Suggestions
                      </h4>
                      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                        {upgradeSuggestions.map((room) => {
                          const statusColors = getStatusColor(room.status);
                          return (
                            <div
                              key={room.id}
                              className={`p-4 rounded-xl border-2 ${statusColors.bg} ${statusColors.border} cursor-pointer hover:shadow-lg transition-all`}
                              onClick={() => handleAssignRoom(room.id, room.room_number)}
                            >
                              <div className="font-bold text-lg">{room.room_number}</div>
                              <div className="text-sm text-gray-700">{room.room_type}</div>
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  )}

                  <div className="bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
                    <div className="flex items-center justify-between mb-6">
                      <h4 className="font-bold text-gray-900">Available Rooms ({availableRoomsForAssignment.length})</h4>
                      {upgradeSuggestions.length > 0 && (
                        <button
                          onClick={() => setShowUpgradeSuggestions(!showUpgradeSuggestions)}
                          className="text-sm text-indigo-600 hover:text-indigo-700 font-medium"
                        >
                          {showUpgradeSuggestions ? 'Hide' : 'Show'} Upgrade Options
                        </button>
                      )}
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                      {availableRoomsForAssignment.map((room) => {
                        const statusColors = getStatusColor(room.status);
                        const isCurrentRoom = room.id === selectedBooking.room_id;
                        return (
                          <div
                            key={room.id}
                            className={`
                              p-5 rounded-xl border-2 transition-all cursor-pointer
                              ${isCurrentRoom 
                                ? 'border-blue-500 bg-blue-50' 
                                : `${statusColors.bg} ${statusColors.border} hover:shadow-lg`
                              }
                              ${assigningRoom ? 'opacity-50 cursor-not-allowed' : ''}
                            `}
                            onClick={() => !isCurrentRoom && !assigningRoom && handleAssignRoom(room.id, room.room_number)}
                          >
                            <div className="flex items-center justify-between mb-2">
                              <div className="font-bold text-xl text-gray-900">{room.room_number}</div>
                              {isCurrentRoom && (
                                <span className="px-2 py-1 bg-blue-600 text-white text-xs font-semibold rounded">
                                  Current
                                </span>
                              )}
                            </div>
                            <div className="text-sm text-gray-700 mb-3">{room.room_type}</div>
                            {!isCurrentRoom && (
                              <button
                                disabled={assigningRoom}
                                className="w-full px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 font-medium disabled:opacity-50 transition-colors"
                              >
                                {assigningRoom ? 'Assigning...' : 'Assign Room'}
                              </button>
                            )}
                          </div>
                        );
                      })}
                    </div>
                  </div>
                </>
              )}
            </div>
          )}
        </div>
      )}

      {/* Maintenance Tab */}
      {activeTab === 'maintenance' && <MaintenanceManagement />}

      {/* Housekeeping Tab */}
      {activeTab === 'housekeeping' && <HousekeepingManagement />}

      {/* Inspections Tab */}
      {activeTab === 'inspections' && <InspectionManagement />}
    </div>
  );
};

export default AdvancedRoomManagementPage;

