import React, { useState, useEffect, useMemo, useCallback } from 'react';
import {
  Hotel,
  Wrench,
  Sparkles,
  ClipboardCheck,
  Filter,
  RefreshCw,
  CheckCircle,
  AlertTriangle,
  Users,
  ChevronDown,
  ChevronUp,
  Calendar,
  MapPin,
  Search,
  Plus,
  Edit,
  Trash2,
  X,
  Image as ImageIcon,
  Check,
} from 'lucide-react';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import advancedRoomService, {
  RoomStatusBoardItem,
} from '../../features/rooms/services/advancedRoomService';
import roomService, { Room } from '../../features/rooms/services/roomService';
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 Pagination from '../../shared/components/Pagination';
import apiClient from '../../shared/services/apiClient';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';
import { logger } from '../../shared/utils/logger';

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

const AdvancedRoomManagementPage: React.FC = () => {
  const { 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());

  // Rooms management state
  const [roomList, setRoomList] = useState<Room[]>([]);
  const [roomsLoading, setRoomsLoading] = useState(true);
  const [showRoomModal, setShowRoomModal] = useState(false);
  const [editingRoom, setEditingRoom] = useState<Room | null>(null);
  const [selectedRooms, setSelectedRooms] = useState<number[]>([]);
  const [roomFilters, setRoomFilters] = useState({
    search: '',
    status: '',
    type: '',
  });
  const [roomCurrentPage, setRoomCurrentPage] = useState(1);
  const [roomTotalPages, setRoomTotalPages] = useState(1);
  const [roomTotalItems, setRoomTotalItems] = useState(0);
  const roomItemsPerPage = 5;
  const [roomFormData, setRoomFormData] = useState({
    room_number: '',
    floor: 1,
    room_type_id: 1,
    status: 'available' as 'available' | 'occupied' | 'maintenance',
    featured: false,
    price: '',
    description: '',
    capacity: '',
    room_size: '',
    view: '',
    amenities: [] as string[],
  });
  const [availableAmenities, setAvailableAmenities] = useState<string[]>([]);
  const [roomTypes, setRoomTypes] = useState<Array<{ id: number; name: string }>>([]);
  const [uploadingImages, setUploadingImages] = useState(false);
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);

  useEffect(() => {
    fetchRoomStatusBoard();
    fetchFloors();
  }, [selectedFloor]);

  const fetchRoomStatusBoard = async () => {
    try {
      setLoading(true);
      const response = await advancedRoomService.getRoomStatusBoard(selectedFloor || undefined);
      if (response.status === 'success') {
        setRooms(response.data.rooms);
      }
    } catch (error: any) {
      toast.error(error.response?.data?.detail || '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: any) => r.floor).filter((f: any) => f != null))
        ).sort((a: any, b: any) => 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';
    }
  };

  // Rooms management functions
  const fetchAvailableAmenities = useCallback(async () => {
    try {
      const response = await roomService.getAmenities();
      if (response.data?.amenities) {
        setAvailableAmenities(response.data.amenities);
      }
    } catch (error) {
      logger.error('Failed to fetch amenities', error);
    }
  }, []);

  const fetchRoomList = useCallback(async () => {
    try {
      setRoomsLoading(true);
      const response = await roomService.getRooms({
        ...roomFilters,
        page: roomCurrentPage,
        limit: roomItemsPerPage,
      });
      setRoomList(response.data.rooms);
      if (response.data.pagination) {
        setRoomTotalPages(response.data.pagination.totalPages);
        setRoomTotalItems(response.data.pagination.total);
      }
      
      const uniqueRoomTypes = new Map<number, { id: number; name: string }>();
      response.data.rooms.forEach((room: Room) => {
        if (room.room_type && !uniqueRoomTypes.has(room.room_type.id)) {
          uniqueRoomTypes.set(room.room_type.id, {
            id: room.room_type.id,
            name: room.room_type.name,
          });
        }
      });
      setRoomTypes(Array.from(uniqueRoomTypes.values()));
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Unable to load rooms list');
    } finally {
      setRoomsLoading(false);
    }
  }, [roomFilters.search, roomFilters.status, roomFilters.type, roomCurrentPage]);

  useEffect(() => {
    setRoomCurrentPage(1);
    setSelectedRooms([]);
  }, [roomFilters.search, roomFilters.status, roomFilters.type]);

  useEffect(() => {
    if (activeTab === 'rooms') {
      fetchRoomList();
      fetchAvailableAmenities();
    }
  }, [activeTab, fetchRoomList, fetchAvailableAmenities]);

  useEffect(() => {
    if (activeTab !== 'rooms') return;
    
    const fetchAllRoomTypes = async () => {
      try {
        const response = await roomService.getRooms({ limit: 100, page: 1 });
        const allUniqueRoomTypes = new Map<number, { id: number; name: string }>();
        response.data.rooms.forEach((room: Room) => {
          if (room.room_type && !allUniqueRoomTypes.has(room.room_type.id)) {
            allUniqueRoomTypes.set(room.room_type.id, {
              id: room.room_type.id,
              name: room.room_type.name,
            });
          }
        });
        
        if (response.data.pagination && response.data.pagination.totalPages > 1) {
          const totalPages = response.data.pagination.totalPages;
          for (let page = 2; page <= totalPages; page++) {
            try {
              const pageResponse = await roomService.getRooms({ limit: 100, page });
              pageResponse.data.rooms.forEach((room: Room) => {
                if (room.room_type && !allUniqueRoomTypes.has(room.room_type.id)) {
                  allUniqueRoomTypes.set(room.room_type.id, {
                    id: room.room_type.id,
                    name: room.room_type.name,
                  });
                }
              });
            } catch (err) {
              logger.error(`Failed to fetch page ${page}`, err);
            }
          }
        }
        
        const roomTypesList = Array.from(allUniqueRoomTypes.values());
        setRoomTypes(roomTypesList);
        setRoomFormData(prev => {
          if (!editingRoom && prev.room_type_id === 1 && roomTypesList.length > 0) {
            return { ...prev, room_type_id: roomTypesList[0].id };
          }
          return prev;
        });
      } catch (error) {
        logger.error('Failed to fetch room types', error);
      }
    };
    
    fetchAllRoomTypes();
  }, [activeTab, editingRoom]);

  const handleRoomSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingRoom) {
        const updateData = {
          ...roomFormData,
          price: roomFormData.price ? parseFloat(roomFormData.price) : undefined,
          description: roomFormData.description || undefined,
          capacity: roomFormData.capacity ? parseInt(roomFormData.capacity) : undefined,
          room_size: roomFormData.room_size || undefined,
          view: roomFormData.view || undefined,
          amenities: Array.isArray(roomFormData.amenities) ? roomFormData.amenities : [],
        };
        await roomService.updateRoom(editingRoom.id, updateData);
        toast.success('Room updated successfully');
        await fetchRoomList();
        try {
          const updatedRoom = await roomService.getRoomByNumber(editingRoom.room_number);
          setEditingRoom(updatedRoom.data.room);
        } catch (err) {
          logger.error('Failed to refresh room data', err);
        }
      } else {
        const createData = {
          ...roomFormData,
          price: roomFormData.price ? parseFloat(roomFormData.price) : undefined,
          description: roomFormData.description || undefined,
          capacity: roomFormData.capacity ? parseInt(roomFormData.capacity) : undefined,
          room_size: roomFormData.room_size || undefined,
          view: roomFormData.view || undefined,
          amenities: Array.isArray(roomFormData.amenities) ? roomFormData.amenities : [],
        };
        const response = await roomService.createRoom(createData);
        toast.success('Room added successfully');
        
        if (response.data?.room) {
          if (selectedFiles.length > 0) {
            try {
              setUploadingImages(true);
              const uploadFormData = new FormData();
              selectedFiles.forEach(file => {
                uploadFormData.append('images', file);
              });
              
              await apiClient.post(`/rooms/${response.data.room.id}/images`, uploadFormData, {
                headers: {
                  'Content-Type': 'multipart/form-data',
                },
              });
              
              toast.success('Images uploaded successfully');
              setSelectedFiles([]);
              const updatedRoom = await roomService.getRoomByNumber(response.data.room.room_number);
              setEditingRoom(updatedRoom.data.room);
            } catch (uploadError: any) {
              toast.error(uploadError.response?.data?.message || 'Room created but failed to upload images');
              const updatedRoom = await roomService.getRoomByNumber(response.data.room.room_number);
              setEditingRoom(updatedRoom.data.room);
            } finally {
              setUploadingImages(false);
            }
          } else {
            const updatedRoom = await roomService.getRoomByNumber(response.data.room.room_number);
            setEditingRoom(updatedRoom.data.room);
          }
          
          setRoomFormData({
            room_number: response.data.room.room_number,
            floor: response.data.room.floor,
            room_type_id: response.data.room.room_type_id,
            status: response.data.room.status,
            featured: response.data.room.featured,
            price: response.data.room.price?.toString() || '',
            description: response.data.room.description || '',
            capacity: response.data.room.capacity?.toString() || '',
            room_size: response.data.room.room_size || '',
            view: response.data.room.view || '',
            amenities: response.data.room.amenities || [],
          });
          
          await fetchRoomList();
          return;
        }
      }
      setShowRoomModal(false);
      resetRoomForm();
      fetchRoomList();
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'An error occurred');
    }
  };

  const handleEditRoom = async (room: Room) => {
    setEditingRoom(room);
    
    let amenitiesArray: string[] = [];
    if (room.amenities) {
      if (Array.isArray(room.amenities)) {
        amenitiesArray = room.amenities;
      } else if (typeof room.amenities === 'string') {
        try {
          const parsed = JSON.parse(room.amenities);
          amenitiesArray = Array.isArray(parsed) ? parsed : [];
        } catch {
          const amenitiesStr: string = room.amenities;
          amenitiesArray = amenitiesStr.split(',').map((a: string) => a.trim()).filter(Boolean);
        }
      }
    }
    
    setRoomFormData({
      room_number: room.room_number,
      floor: room.floor,
      room_type_id: room.room_type_id,
      status: room.status,
      featured: room.featured,
      price: room.price?.toString() || '',
      description: room.description || '',
      capacity: room.capacity?.toString() || '',
      room_size: room.room_size || '',
      view: room.view || '',
      amenities: amenitiesArray,
    });
    
    setShowRoomModal(true);
    
    try {
      const fullRoom = await roomService.getRoomByNumber(room.room_number);
      const roomData = fullRoom.data.room;
      
      let updatedAmenitiesArray: string[] = [];
      if (roomData.amenities) {
        if (Array.isArray(roomData.amenities)) {
          updatedAmenitiesArray = roomData.amenities;
        } else if (typeof roomData.amenities === 'string') {
          try {
            const parsed = JSON.parse(roomData.amenities);
            updatedAmenitiesArray = Array.isArray(parsed) ? parsed : [];
          } catch {
            const amenitiesStr: string = roomData.amenities;
            updatedAmenitiesArray = amenitiesStr.split(',').map((a: string) => a.trim()).filter(Boolean);
          }
        }
      }
      
      setRoomFormData({
        room_number: roomData.room_number,
        floor: roomData.floor,
        room_type_id: roomData.room_type_id,
        status: roomData.status,
        featured: roomData.featured,
        price: roomData.price?.toString() || '',
        description: roomData.description || '',
        capacity: roomData.capacity?.toString() || '',
        room_size: roomData.room_size || '',
        view: roomData.view || '',
        amenities: updatedAmenitiesArray,
      });
      
      setEditingRoom(roomData);
    } catch (error) {
      logger.error('Failed to fetch full room details', error);
    }
  };

  const handleDeleteRoom = async (id: number) => {
    if (!window.confirm('Are you sure you want to delete this room?')) return;
    
    try {
      await roomService.deleteRoom(id);
      toast.success('Room deleted successfully');
      setSelectedRooms(selectedRooms.filter(roomId => roomId !== id));
      fetchRoomList();
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Unable to delete room');
    }
  };

  const handleBulkDeleteRooms = async () => {
    if (selectedRooms.length === 0) {
      toast.warning('Please select at least one room to delete');
      return;
    }
    
    if (!window.confirm(`Are you sure you want to delete ${selectedRooms.length} room(s)?`)) return;
    
    try {
      await roomService.bulkDeleteRooms(selectedRooms);
      toast.success(`Successfully deleted ${selectedRooms.length} room(s)`);
      setSelectedRooms([]);
      fetchRoomList();
    } catch (error: any) {
      toast.error(error.response?.data?.message || error.response?.data?.detail || 'Unable to delete rooms');
    }
  };

  const handleSelectRoom = (roomId: number) => {
    setSelectedRooms(prev => 
      prev.includes(roomId) 
        ? prev.filter(id => id !== roomId)
        : [...prev, roomId]
    );
  };

  const handleSelectAllRooms = () => {
    if (selectedRooms.length === roomList.length) {
      setSelectedRooms([]);
    } else {
      setSelectedRooms(roomList.map(room => room.id));
    }
  };

  const resetRoomForm = () => {
    setEditingRoom(null);
    setRoomFormData({
      room_number: '',
      floor: 1,
      room_type_id: 1,
      status: 'available',
      featured: false,
      price: '',
      description: '',
      capacity: '',
      room_size: '',
      view: '',
      amenities: [],
    });
    setSelectedFiles([]);
    setUploadingImages(false);
  };

  const toggleAmenity = (amenity: string) => {
    setRoomFormData(prev => ({
      ...prev,
      amenities: prev.amenities.includes(amenity)
        ? prev.amenities.filter(a => a !== amenity)
        : [...prev.amenities, amenity]
    }));
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      const files = Array.from(e.target.files);
      setSelectedFiles(files);
    }
  };

  const handleUploadImages = async () => {
    if (!editingRoom || selectedFiles.length === 0) return;

    try {
      setUploadingImages(true);
      const formData = new FormData();
      selectedFiles.forEach(file => {
        formData.append('images', file);
      });

      await apiClient.post(`/rooms/${editingRoom.id}/images`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      toast.success('Images uploaded successfully');
      setSelectedFiles([]);
      fetchRoomList();
      
      const response = await roomService.getRoomByNumber(editingRoom.room_number);
      setEditingRoom(response.data.room);
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Unable to upload images');
    } finally {
      setUploadingImages(false);
    }
  };

  const handleDeleteImage = async (imageUrl: string) => {
    if (!editingRoom) return;
    if (!window.confirm('Are you sure you want to delete this image?')) return;

    try {
      let imagePath = imageUrl;
      if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
        try {
          const url = new URL(imageUrl);
          imagePath = url.pathname;
        } catch (e) {
          const match = imageUrl.match(/(\/uploads\/.*)/);
          imagePath = match ? match[1] : imageUrl;
        }
      }

      await apiClient.delete(`/rooms/${editingRoom.id}/images`, {
        params: { image_url: imagePath },
      });

      toast.success('Image deleted successfully');
      fetchRoomList();
      
      const response = await roomService.getRoomByNumber(editingRoom.room_number);
      setEditingRoom(response.data.room);
    } catch (error: any) {
      logger.error('Error deleting image', error);
      toast.error(error.response?.data?.message || error.response?.data?.detail || 'Unable to delete image');
    }
  };

  const getRoomStatusBadge = (status: string) => {
    const badges: Record<string, { bg: string; text: string; label: string; border: string }> = {
      available: { 
        bg: 'bg-gradient-to-r from-emerald-50 to-green-50', 
        text: 'text-emerald-800', 
        label: 'Available',
        border: 'border-emerald-200'
      },
      occupied: { 
        bg: 'bg-gradient-to-r from-blue-50 to-indigo-50', 
        text: 'text-blue-800', 
        label: 'Occupied',
        border: 'border-blue-200'
      },
      maintenance: { 
        bg: 'bg-gradient-to-r from-amber-50 to-yellow-50', 
        text: 'text-amber-800', 
        label: 'Maintenance',
        border: 'border-amber-200'
      },
    };
    const badge = badges[status] || badges.available;
    return (
      <span className={`px-4 py-1.5 rounded-full text-xs font-semibold border shadow-sm ${badge.bg} ${badge.text} ${badge.border}`}>
        {badge.label}
      </span>
    );
  };

  if (loading && rooms.length === 0 && activeTab !== 'rooms') {
    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: 'rooms' as Tab, label: 'Rooms', icon: Hotel },
            { 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>
      )}

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

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

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

      {/* Rooms Tab */}
      {activeTab === 'rooms' && (
        <div className="space-y-8">
          {roomsLoading && <Loading />}

          <div className="bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
            <div className="flex justify-between items-center">
              <div className="space-y-3">
                <div className="flex items-center gap-3">
                  <div className="p-2.5 rounded-xl bg-gradient-to-br from-amber-500/10 to-yellow-500/10 border border-amber-200/40">
                    <Hotel className="w-6 h-6 text-amber-600" />
                  </div>
                  <h2 className="text-xl sm:text-2xl md:text-2xl font-extrabold text-gray-900">Room Management</h2>
                </div>
                <p className="text-gray-600 text-base max-w-2xl leading-relaxed">
                  Manage hotel room information and availability
                </p>
              </div>
              <div className="flex gap-3">
                {selectedRooms.length > 0 && (
                  <button
                    onClick={handleBulkDeleteRooms}
                    className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-rose-500 to-rose-600 text-white rounded-xl font-semibold hover:from-rose-600 hover:to-rose-700 transition-all duration-200 shadow-lg hover:shadow-xl"
                  >
                    <Trash2 className="w-5 h-5" />
                    Delete Selected ({selectedRooms.length})
                  </button>
                )}
                <button
                  onClick={() => {
                    resetRoomForm();
                    setShowRoomModal(true);
                  }}
                  className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-xl font-semibold hover:from-amber-600 hover:to-amber-700 transition-all duration-200 shadow-lg hover:shadow-xl"
                >
                  <Plus className="w-5 h-5" />
                  Add Room
                </button>
              </div>
            </div>
          </div>

          <div className="bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-6">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
              <div className="relative group">
                <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5 group-focus-within:text-amber-500 transition-colors" />
                <input
                  type="text"
                  placeholder="Search rooms..."
                  value={roomFilters.search}
                  onChange={(e) => setRoomFilters({ ...roomFilters, search: e.target.value })}
                  className="w-full pl-12 pr-4 py-3.5 bg-white border-2 border-gray-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-gray-700 placeholder-gray-400 font-medium shadow-sm hover:shadow-md"
                />
              </div>
              <select
                value={roomFilters.status}
                onChange={(e) => setRoomFilters({ ...roomFilters, status: e.target.value })}
                className="px-4 py-3.5 bg-white border-2 border-gray-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-gray-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
              >
                <option value="">All Statuses</option>
                <option value="available">Available</option>
                <option value="occupied">Occupied</option>
                <option value="maintenance">Maintenance</option>
              </select>
              <select
                value={roomFilters.type}
                onChange={(e) => setRoomFilters({ ...roomFilters, type: e.target.value })}
                className="px-4 py-3.5 bg-white border-2 border-gray-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-gray-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
              >
                <option value="">All Room Types</option>
                {roomTypes.map((roomType) => (
                  <option key={roomType.id} value={roomType.name}>
                    {roomType.name}
                  </option>
                ))}
              </select>
            </div>
          </div>

          <div className="bg-white/90 backdrop-blur-xl rounded-xl sm:rounded-2xl shadow-xl border border-gray-200/50 overflow-hidden">
            <div className="overflow-x-auto -mx-2 sm:mx-0 px-2 sm:px-0">
              <table className="w-full min-w-[800px] sm:min-w-full">
                <thead>
                  <tr className="bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900">
                    <th className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700 w-12">
                      <input
                        type="checkbox"
                        checked={roomList.length > 0 && selectedRooms.length === roomList.length}
                        onChange={handleSelectAllRooms}
                        title="Select all rooms"
                        className="w-4 h-4 sm:w-5 sm:h-5 text-amber-600 bg-slate-700 border-slate-600 rounded focus:ring-amber-500 cursor-pointer"
                      />
                    </th>
                    <th className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Room Number</th>
                    <th className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Room Type</th>
                    <th className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Floor</th>
                    <th className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Price</th>
                    <th className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Status</th>
                    <th className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Featured</th>
                    <th className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 text-right text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Actions</th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-slate-100">
                  {roomList.map((room) => (
                    <tr 
                      key={room.id} 
                      className={`hover:bg-gradient-to-r hover:from-amber-50/30 hover:to-yellow-50/30 transition-all duration-200 group border-b border-slate-100 ${selectedRooms.includes(room.id) ? 'bg-amber-50/50' : ''}`}
                    >
                      <td className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 whitespace-nowrap">
                        <input
                          type="checkbox"
                          checked={selectedRooms.includes(room.id)}
                          onChange={() => handleSelectRoom(room.id)}
                          className="w-4 h-4 sm:w-5 sm:h-5 text-amber-600 bg-white border-slate-300 rounded focus:ring-amber-500 cursor-pointer"
                          title={`Select room ${room.room_number}`}
                        />
                      </td>
                      <td className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 whitespace-nowrap">
                        <div className="text-xs sm:text-sm font-bold text-gray-900 font-mono">{room.room_number}</div>
                      </td>
                      <td className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 whitespace-nowrap">
                        <div className="text-xs sm:text-sm font-medium text-gray-900">{room.room_type?.name || 'N/A'}</div>
                      </td>
                      <td className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 whitespace-nowrap">
                        <div className="text-xs sm:text-sm text-gray-700">Floor {room.floor}</div>
                      </td>
                      <td className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 whitespace-nowrap">
                        <div className="text-xs sm:text-sm font-bold bg-gradient-to-r from-emerald-600 to-emerald-700 bg-clip-text text-transparent">
                          {formatCurrency(room.price || room.room_type?.base_price || 0)}
                        </div>
                      </td>
                      <td className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 whitespace-nowrap">
                        {getRoomStatusBadge(room.status)}
                      </td>
                      <td className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 whitespace-nowrap">
                        {room.featured ? (
                          <span className="text-amber-500 text-base sm:text-lg">⭐</span>
                        ) : (
                          <span className="text-gray-400">-</span>
                        )}
                      </td>
                      <td className="px-3 sm:px-4 md:px-6 lg:px-8 py-3 sm:py-4 md:py-5 whitespace-nowrap text-right">
                        <div className="flex items-center justify-end gap-1 sm:gap-2">
                          <button
                            onClick={() => handleEditRoom(room)}
                            className="p-1.5 sm:p-2 rounded-lg text-blue-600 hover:text-blue-700 hover:bg-blue-50 transition-all duration-200 shadow-sm hover:shadow-md border border-blue-200 hover:border-blue-300"
                            title="Edit"
                          >
                            <Edit className="w-4 h-4 sm:w-5 sm:h-5" />
                          </button>
                          <button
                            onClick={() => handleDeleteRoom(room.id)}
                            className="p-1.5 sm:p-2 rounded-lg text-rose-600 hover:text-rose-700 hover:bg-rose-50 transition-all duration-200 shadow-sm hover:shadow-md border border-rose-200 hover:border-rose-300"
                            title="Delete"
                          >
                            <Trash2 className="w-4 h-4 sm:w-5 sm:h-5" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <Pagination
              currentPage={roomCurrentPage}
              totalPages={roomTotalPages}
              onPageChange={setRoomCurrentPage}
              totalItems={roomTotalItems}
              itemsPerPage={roomItemsPerPage}
            />
          </div>

          {showRoomModal && (
            <div className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center z-50 p-4">
              <div className="bg-gradient-to-br from-[#1a1a1a] via-[#0f0f0f] to-[#1a1a1a] rounded-xl border border-[#d4af37]/30 backdrop-blur-xl shadow-2xl shadow-[#d4af37]/20 p-8 w-full max-w-4xl max-h-[90vh] overflow-y-auto">
                <div className="flex justify-between items-center mb-6 pb-6 border-b border-[#d4af37]/20">
                  <div>
                    <h2 className="text-xl sm:text-2xl md:text-2xl font-serif font-semibold bg-gradient-to-r from-white via-[#d4af37] to-white bg-clip-text text-transparent tracking-wide">
                      {editingRoom ? 'Update Room' : 'Add New Room'}
                    </h2>
                    <p className="text-gray-400 text-sm mt-1 font-light">
                      {editingRoom ? 'Modify room details and amenities' : 'Create a new luxurious room'}
                    </p>
                  </div>
                  <button 
                    onClick={() => setShowRoomModal(false)}
                    className="p-2 hover:bg-[#d4af37]/10 rounded-lg transition-colors border border-[#d4af37]/20 hover:border-[#d4af37]/40"
                  >
                    <X className="w-6 h-6 text-[#d4af37] hover:text-white transition-colors" />
                  </button>
                </div>
                
                <form onSubmit={handleRoomSubmit} className="space-y-6">
                  <div className="space-y-4">
                    <h3 className="text-lg font-serif font-semibold text-[#d4af37] mb-4 flex items-center gap-2">
                      <div className="w-1 h-6 bg-gradient-to-b from-[#d4af37] to-[#c9a227]" />
                      Basic Information
                    </h3>
                    
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="block text-sm font-medium text-gray-300 mb-2">
                          Room Number
                        </label>
                        <input
                          type="text"
                          value={roomFormData.room_number}
                          onChange={(e) => setRoomFormData({ ...roomFormData, room_number: e.target.value })}
                          className="w-full px-4 py-3 bg-[#0a0a0a] border border-[#d4af37]/20 rounded-lg text-white placeholder-gray-500 focus:ring-2 focus:ring-[#d4af37]/50 focus:border-[#d4af37] transition-all duration-300"
                          placeholder="e.g., 1001"
                          required
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-300 mb-2">
                          Floor
                        </label>
                        <input
                          type="number"
                          value={roomFormData.floor}
                          onChange={(e) => setRoomFormData({ ...roomFormData, floor: parseInt(e.target.value) })}
                          className="w-full px-4 py-3 bg-[#0a0a0a] border border-[#d4af37]/20 rounded-lg text-white placeholder-gray-500 focus:ring-2 focus:ring-[#d4af37]/50 focus:border-[#d4af37] transition-all duration-300"
                          required
                          min="1"
                        />
                      </div>
                    </div>
                    
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        Room Type
                      </label>
                      <select
                        value={roomFormData.room_type_id}
                        onChange={(e) => setRoomFormData({ ...roomFormData, room_type_id: parseInt(e.target.value) })}
                        className="w-full px-4 py-3 bg-[#0a0a0a] border border-[#d4af37]/20 rounded-lg text-white focus:ring-2 focus:ring-[#d4af37]/50 focus:border-[#d4af37] transition-all duration-300"
                        required
                      >
                        {roomTypes.length > 0 ? (
                          roomTypes.map((roomType) => (
                            <option key={roomType.id} value={roomType.id} className="bg-[#1a1a1a]">
                              {roomType.name}
                            </option>
                          ))
                        ) : (
                          <option value="" className="bg-[#1a1a1a]">Loading...</option>
                        )}
                      </select>
                    </div>
                    
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        Status
                      </label>
                      <select
                        value={roomFormData.status}
                        onChange={(e) => setRoomFormData({ ...roomFormData, status: e.target.value as any })}
                        className="w-full px-4 py-3 bg-[#0a0a0a] border border-[#d4af37]/20 rounded-lg text-white focus:ring-2 focus:ring-[#d4af37]/50 focus:border-[#d4af37] transition-all duration-300"
                        required
                      >
                        <option value="available" className="bg-[#1a1a1a]">Available</option>
                        <option value="occupied" className="bg-[#1a1a1a]">Occupied</option>
                        <option value="maintenance" className="bg-[#1a1a1a]">Maintenance</option>
                      </select>
                    </div>
                    
                    <div className="flex items-center gap-3 p-4 bg-[#0a0a0a] rounded-lg border border-[#d4af37]/20">
                      <input
                        type="checkbox"
                        id="featured"
                        checked={roomFormData.featured}
                        onChange={(e) => setRoomFormData({ ...roomFormData, featured: e.target.checked })}
                        className="w-5 h-5 text-[#d4af37] bg-[#1a1a1a] border-[#d4af37]/30 rounded focus:ring-[#d4af37]/50 focus:ring-2 cursor-pointer transition-all"
                      />
                      <label htmlFor="featured" className="text-sm text-gray-300 cursor-pointer font-medium">
                        Featured Room
                      </label>
                    </div>
                    
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        Room Price
                      </label>
                      <input
                        type="number"
                        step="0.01"
                        min="0"
                        value={roomFormData.price}
                        onChange={(e) => setRoomFormData({ ...roomFormData, price: e.target.value })}
                        className="w-full px-4 py-3 bg-[#0a0a0a] border border-[#d4af37]/20 rounded-lg text-white placeholder-gray-500 focus:ring-2 focus:ring-[#d4af37]/50 focus:border-[#d4af37] transition-all duration-300"
                        placeholder="e.g., 150.00"
                      />
                    </div>
                    
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        Room Description
                      </label>
                      <textarea
                        value={roomFormData.description}
                        onChange={(e) => setRoomFormData({ ...roomFormData, description: e.target.value })}
                        rows={4}
                        className="w-full px-4 py-3 bg-[#0a0a0a] border border-[#d4af37]/20 rounded-lg text-white placeholder-gray-500 focus:ring-2 focus:ring-[#d4af37]/50 focus:border-[#d4af37] transition-all duration-300 resize-none"
                        placeholder="Enter the actual description for this specific room..."
                      />
                    </div>
                    
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="block text-sm font-medium text-gray-300 mb-2">
                          Max Guests (Capacity)
                        </label>
                        <input
                          type="number"
                          min="1"
                          value={roomFormData.capacity}
                          onChange={(e) => setRoomFormData({ ...roomFormData, capacity: e.target.value })}
                          className="w-full px-4 py-3 bg-[#0a0a0a] border border-[#d4af37]/20 rounded-lg text-white placeholder-gray-500 focus:ring-2 focus:ring-[#d4af37]/50 focus:border-[#d4af37] transition-all duration-300"
                          placeholder="e.g., 4"
                        />
                      </div>
                      
                      <div>
                        <label className="block text-sm font-medium text-gray-300 mb-2">
                          Room Size
                        </label>
                        <input
                          type="text"
                          value={roomFormData.room_size}
                          onChange={(e) => setRoomFormData({ ...roomFormData, room_size: e.target.value })}
                          className="w-full px-4 py-3 bg-[#0a0a0a] border border-[#d4af37]/20 rounded-lg text-white placeholder-gray-500 focus:ring-2 focus:ring-[#d4af37]/50 focus:border-[#d4af37] transition-all duration-300"
                          placeholder="e.g., 1 Room, 50 sqm"
                        />
                      </div>
                    </div>
                    
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        View
                      </label>
                      <input
                        type="text"
                        value={roomFormData.view}
                        onChange={(e) => setRoomFormData({ ...roomFormData, view: e.target.value })}
                        className="w-full px-4 py-3 bg-[#0a0a0a] border border-[#d4af37]/20 rounded-lg text-white placeholder-gray-500 focus:ring-2 focus:ring-[#d4af37]/50 focus:border-[#d4af37] transition-all duration-300"
                        placeholder="e.g., City View, Ocean View, Mountain View"
                      />
                    </div>
                  </div>

                  <div className="space-y-4">
                    <h3 className="text-lg font-serif font-semibold text-[#d4af37] mb-4 flex items-center gap-2">
                      <div className="w-1 h-6 bg-gradient-to-b from-[#d4af37] to-[#c9a227]" />
                      Amenities & Features
                    </h3>
                    
                    <div className="border border-[#d4af37]/20 rounded-lg p-4 max-h-80 overflow-y-auto bg-[#0a0a0a]/50 backdrop-blur-sm">
                      {availableAmenities.length === 0 ? (
                        <p className="text-sm text-gray-400 text-center py-4">Loading amenities...</p>
                      ) : (
                        <div className="grid grid-cols-2 gap-3">
                          {availableAmenities.map((amenity) => {
                            const isSelected = roomFormData.amenities.includes(amenity);
                            return (
                              <label
                                key={amenity}
                                className={`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all duration-300 ${
                                  isSelected
                                    ? 'bg-gradient-to-r from-[#d4af37]/20 to-[#c9a227]/20 border-2 border-[#d4af37] shadow-lg shadow-[#d4af37]/20'
                                    : 'bg-[#1a1a1a]/50 border-2 border-[#333] hover:border-[#d4af37]/30 hover:bg-[#1a1a1a]'
                                }`}
                              >
                                <input
                                  type="checkbox"
                                  checked={isSelected}
                                  onChange={() => toggleAmenity(amenity)}
                                  className="hidden"
                                />
                                <div className={`w-5 h-5 rounded border-2 flex items-center justify-center transition-all duration-300 ${
                                  isSelected
                                    ? 'bg-[#d4af37] border-[#d4af37] shadow-lg shadow-[#d4af37]/30'
                                    : 'border-gray-600 bg-transparent'
                                }`}>
                                  {isSelected && <Check className="w-3 h-3 text-[#0f0f0f] font-bold" />}
                                </div>
                                <span className={`text-sm flex-1 transition-colors ${
                                  isSelected 
                                    ? 'font-semibold text-[#d4af37]' 
                                    : 'text-gray-400 hover:text-gray-300'
                                }`}>
                                  {amenity}
                                </span>
                              </label>
                            );
                          })}
                        </div>
                      )}
                    </div>
                    {roomFormData.amenities.length > 0 && (
                      <p className="text-xs text-gray-400 font-light italic">
                        {roomFormData.amenities.length} amenit{roomFormData.amenities.length === 1 ? 'y' : 'ies'} selected
                      </p>
                    )}
                  </div>
                  
                  <div className="flex gap-4 pt-4 border-t border-[#d4af37]/20">
                    <button
                      type="button"
                      onClick={() => setShowRoomModal(false)}
                      className="flex-1 px-6 py-3 border border-[#d4af37]/30 text-gray-300 rounded-lg hover:bg-[#d4af37]/10 hover:border-[#d4af37] transition-all duration-300 font-medium"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      className="flex-1 px-6 py-3 bg-gradient-to-r from-[#d4af37] to-[#c9a227] text-[#0f0f0f] rounded-lg hover:from-[#f5d76e] hover:to-[#d4af37] transition-all duration-300 font-semibold shadow-lg shadow-[#d4af37]/30 hover:shadow-xl hover:shadow-[#d4af37]/40"
                    >
                      {editingRoom ? 'Update Room' : 'Add Room'}
                    </button>
                  </div>
                </form>

                {editingRoom && (
                  <div className="mt-8 pt-8 border-t border-[#d4af37]/20">
                    <h3 className="text-lg font-serif font-semibold text-[#d4af37] mb-6 flex items-center gap-2">
                      <div className="w-1 h-6 bg-gradient-to-b from-[#d4af37] to-[#c9a227]" />
                      <ImageIcon className="w-5 h-5" />
                      Room Images
                    </h3>
                    
                    {(() => {
                      const apiBaseUrl = import.meta.env.VITE_API_URL?.replace('/api', '') || 'http://localhost:8000';
                      
                      const normalizeImageUrl = (img: string): string => {
                        if (!img) return '';
                        
                        if (img.startsWith('http://') || img.startsWith('https://')) {
                          return img;
                        }
                        
                        const cleanPath = img.startsWith('/') ? img : `/${img}`;
                        return `${apiBaseUrl}${cleanPath}`;
                      };

                      const roomImages = editingRoom.images || [];
                      const roomTypeImages = editingRoom.room_type?.images || [];
                      
                      const normalizeForComparison = (img: string): string => {
                        if (!img) return '';
                        
                        if (img.startsWith('http://') || img.startsWith('https://')) {
                          try {
                            const url = new URL(img);
                            return url.pathname;
                          } catch {
                            const match = img.match(/(\/uploads\/.*)/);
                            return match ? match[1] : img;
                          }
                        }
                        return img.startsWith('/') ? img : `/${img}`;
                      };

                      const normalizedRoomImages = roomImages.map(normalizeForComparison);
                      const allImages = [
                        ...roomImages,
                        ...roomTypeImages.filter(img => {
                          const normalized = normalizeForComparison(img);
                          return !normalizedRoomImages.includes(normalized);
                        })
                      ];

                      return (
                        <>
                          {allImages.length > 0 ? (
                            <div className="mb-6">
                              <p className="text-sm text-gray-400 mb-4 font-light">
                                Current Images ({allImages.length}):
                              </p>
                              <div className="grid grid-cols-3 gap-4">
                                {allImages.map((img, index) => {
                                  const imageUrl = normalizeImageUrl(img);
                                  
                                  const normalizedImg = normalizeForComparison(img);
                                  const normalizedRoomImgs = roomImages.map(normalizeForComparison);
                                  const isRoomImage = normalizedRoomImgs.includes(normalizedImg);
                                  
                                  return (
                                    <div key={index} className="relative group">
                                      <div className="overflow-hidden rounded-lg border border-[#d4af37]/20 
                                        hover:border-[#d4af37] transition-all duration-300">
                                        <img
                                          src={imageUrl}
                                          alt={`Room Image ${index + 1}`}
                                          className="w-full h-32 object-cover group-hover:scale-110 
                                            transition-transform duration-300"
                                          onError={(e) => {
                                            (e.target as HTMLImageElement).src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgZmlsbD0iIzMzMzMzMyIvPjx0ZXh0IHg9IjUwJSIgeT0iNTAlIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMTQiIGZpbGw9IiM2NjY2NjYiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj5JbWFnZSBub3QgZm91bmQ8L3RleHQ+PC9zdmc+';
                                          }}
                                        />
                                      </div>
                                      {isRoomImage && (
                                        <>
                                          <div className="absolute top-2 left-2 bg-[#d4af37]/90 backdrop-blur-sm 
                                            text-[#0f0f0f] px-2 py-1 rounded text-xs font-semibold 
                                            opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                                            Room Image
                                          </div>
                                          <button
                                            type="button"
                                            onClick={() => handleDeleteImage(img)}
                                            className="absolute top-2 right-2 bg-red-600/90 backdrop-blur-sm 
                                              text-white p-2 rounded-full opacity-0 group-hover:opacity-100 
                                              transition-all duration-300 hover:bg-red-600 shadow-lg
                                              hover:scale-110 transform"
                                          >
                                            <X className="w-4 h-4" />
                                          </button>
                                        </>
                                      )}
                                    </div>
                                  );
                                })}
                              </div>
                            </div>
                          ) : (
                            <div className="mb-6 p-8 bg-[#0a0a0a]/50 rounded-lg border border-[#d4af37]/10 text-center">
                              <ImageIcon className="w-12 h-12 text-gray-600 mx-auto mb-3" />
                              <p className="text-sm text-gray-400 font-light">
                                No images uploaded yet. Upload images below to display them here.
                              </p>
                            </div>
                          )}
                        </>
                      );
                    })()}

                    <div className="space-y-4">
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        Add New Images (max 5 images):
                      </label>
                      <div className="flex gap-4">
                        <div className="flex-1">
                          <input
                            type="file"
                            accept="image/*"
                            multiple
                            onChange={handleFileSelect}
                            className="w-full text-sm text-gray-400 
                              file:mr-4 file:py-3 file:px-6 file:rounded-lg file:border-0 
                              file:text-sm file:font-semibold 
                              file:bg-gradient-to-r file:from-[#d4af37]/20 file:to-[#c9a227]/20 
                              file:text-[#d4af37] file:border file:border-[#d4af37]/30
                              hover:file:from-[#d4af37]/30 hover:file:to-[#c9a227]/30 
                              hover:file:border-[#d4af37] file:cursor-pointer
                              transition-all duration-300 bg-[#0a0a0a] rounded-lg"
                          />
                        </div>
                      </div>
                      {selectedFiles.length > 0 && (
                        <div className="flex items-center gap-4">
                          <p className="text-sm text-gray-400 font-light italic">
                            {selectedFiles.length} file(s) selected
                          </p>
                          <button
                            type="button"
                            onClick={handleUploadImages}
                            disabled={uploadingImages}
                            className="px-6 py-2 bg-gradient-to-r from-[#d4af37] to-[#c9a227] text-[#0f0f0f] rounded-lg hover:from-[#f5d76e] hover:to-[#d4af37] transition-all duration-300 font-semibold shadow-lg shadow-[#d4af37]/30 hover:shadow-xl hover:shadow-[#d4af37]/40 disabled:opacity-50 disabled:cursor-not-allowed"
                          >
                            {uploadingImages ? 'Uploading...' : 'Upload Images'}
                          </button>
                        </div>
                      )}
                    </div>
                  </div>
                )}
                
                <div className="mt-8 pt-6 border-t border-[#d4af37]/20 flex justify-end">
                  <button
                    type="button"
                    onClick={() => {
                      setShowRoomModal(false);
                      resetRoomForm();
                    }}
                    className="px-8 py-3 bg-gradient-to-r from-gray-600 to-gray-700 text-white rounded-lg hover:from-gray-700 hover:to-gray-800 transition-all duration-300 font-semibold shadow-lg shadow-gray-600/30 hover:shadow-xl hover:shadow-gray-600/40 border border-gray-500/30"
                  >
                    Close
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default AdvancedRoomManagementPage;

