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

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

const AdvancedRoomManagementPage: React.FC = () => {
  const navigate = useNavigate();
  const { formatCurrency } = useFormatCurrency();
  const {
    statusBoardRooms,
    statusBoardLoading,
    rooms: contextRooms,
    refreshStatusBoard,
    refreshRooms,
    updateRoom: contextUpdateRoom,
    deleteRoom: contextDeleteRoom,
    createRoom: contextCreateRoom,
    setStatusBoardFloor,
    statusBoardFloor,
  } = useRoomContext();
  
  const [activeTab, setActiveTab] = useState<Tab>('status-board');
  const [selectedFloor, setSelectedFloor] = useState<number | null>(null);
  const [floors, setFloors] = useState<number[]>([]);
  const [expandedRooms, setExpandedRooms] = useState<Set<number>>(new Set());

  // Rooms management state
  const [showRoomModal, setShowRoomModal] = useState(false);
  const [editingRoom, setEditingRoom] = useState<Room | null>(null);
  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[]>([]);
  const [customAmenityInput, setCustomAmenityInput] = useState('');
  const [editingAmenity, setEditingAmenity] = useState<{ name: string; newName: string } | null>(null);

  // Room Types management state
  const [roomTypesList, setRoomTypesList] = useState<RoomType[]>([]);
  const [roomTypesLoading, setRoomTypesLoading] = useState(false);
  const [showRoomTypeModal, setShowRoomTypeModal] = useState(false);
  const [editingRoomType, setEditingRoomType] = useState<RoomType | null>(null);
  const [roomTypeFormData, setRoomTypeFormData] = useState<CreateRoomTypeData>({
    name: '',
    description: '',
    base_price: 0,
    capacity: 1,
    amenities: [],
  });
  const [roomTypeSearchFilter, setRoomTypeSearchFilter] = useState('');
  const [customRoomTypeAmenityInput, setCustomRoomTypeAmenityInput] = useState('');

  // Define fetchFloors before using it in useEffect
  const fetchFloors = useCallback(async () => {
    try {
      const response = await roomService.getRooms({ limit: 100, page: 1 });
      if (response.data?.rooms) {
        const uniqueFloors = Array.from(
          new Set(response.data.rooms.map((r: Room) => r.floor).filter((f: number | undefined) => f != null))
        ).sort((a: number, b: number) => a - b) as number[];
        setFloors(uniqueFloors);
      }
    } catch (error) {
      logger.error('Failed to fetch floors', error);
      toast.error('Failed to load floor information');
    }
  }, []);

  // Sync selectedFloor with context
  useEffect(() => {
    setStatusBoardFloor(selectedFloor);
  }, [selectedFloor, setStatusBoardFloor]);

  // Use rooms directly from context - no need for local state

  // Update selectedFloor when context changes
  useEffect(() => {
    if (statusBoardFloor !== selectedFloor) {
      setSelectedFloor(statusBoardFloor);
    }
  }, [statusBoardFloor, selectedFloor]);

  // Refresh status board when floor filter changes
  useEffect(() => {
    let isMounted = true;
    const abortController = new AbortController();

    const refresh = async () => {
      if (isMounted && !abortController.signal.aborted) {
        await refreshStatusBoard(selectedFloor || undefined);
      }
    };

    refresh();

    return () => {
      isMounted = false;
      abortController.abort();
    };
  }, [selectedFloor, refreshStatusBoard]);

  useEffect(() => {
    let isMounted = true;
    const abortController = new AbortController();

    const initializeData = async () => {
      try {
        await Promise.all([
          fetchFloors(),
          refreshStatusBoard(),
        ]);
      } catch (error) {
        if (isMounted && !abortController.signal.aborted) {
          logger.error('Error initializing data', error);
        }
      }
    };

    initializeData();

    return () => {
      isMounted = false;
      abortController.abort();
    };
  }, [refreshStatusBoard, fetchFloors]);

  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[]> = {};
    statusBoardRooms.forEach(room => {
      if (!grouped[room.floor]) {
        grouped[room.floor] = [];
      }
      grouped[room.floor].push(room);
    });
    return grouped;
  }, [statusBoardRooms]);

  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);
      toast.error('Failed to load amenities');
    }
  }, []);


  // Fetch room types using dedicated endpoint
  const fetchRoomTypes = useCallback(async () => {
    try {
      const response = await roomService.getRoomTypes();
      if (response.data?.room_types) {
        const roomTypesList = response.data.room_types.map((rt: { id: number; name: string }) => ({
          id: rt.id,
          name: rt.name,
        }));
        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);
      toast.error('Failed to load room types');
    }
  }, [editingRoom]);

  // Helper function to ensure amenities is always an array
  const getAmenitiesArray = (amenities: any): string[] => {
    if (!amenities) return [];
    if (Array.isArray(amenities)) return amenities;
    if (typeof amenities === 'string') {
      try {
        const parsed = JSON.parse(amenities);
        return Array.isArray(parsed) ? parsed : [];
      } catch {
        return [];
      }
    }
    return [];
  };

  // Fetch room types for management tab
  const fetchRoomTypesList = useCallback(async () => {
    try {
      setRoomTypesLoading(true);
      const response = await roomService.getRoomTypes();
      if (response.data?.room_types) {
        setRoomTypesList(response.data.room_types);
      }
    } catch (error: any) {
      logger.error('Failed to fetch room types', error);
      toast.error(error.response?.data?.detail || 'Unable to load room types');
    } finally {
      setRoomTypesLoading(false);
    }
  }, []);

  // Room Type management functions
  const handleRoomTypeSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingRoomType) {
        await roomService.updateRoomType(editingRoomType.id, roomTypeFormData);
        toast.success('Room type updated successfully');
      } else {
        await roomService.createRoomType(roomTypeFormData);
        toast.success('Room type created successfully');
      }
      setShowRoomTypeModal(false);
      resetRoomTypeForm();
      fetchRoomTypesList();
      fetchRoomTypes(); // Refresh dropdown list
    } catch (error: any) {
      toast.error(error.response?.data?.detail || 'An error occurred');
    }
  };

  const handleRoomTypeEdit = (roomType: RoomType) => {
    setEditingRoomType(roomType);
    setRoomTypeFormData({
      name: roomType.name,
      description: roomType.description || '',
      base_price: roomType.base_price,
      capacity: roomType.capacity,
      amenities: getAmenitiesArray(roomType.amenities),
    });
    setShowRoomTypeModal(true);
  };

  const handleRoomTypeDelete = async (id: number) => {
    if (!window.confirm('Are you sure you want to delete this room type? This action cannot be undone.')) {
      return;
    }

    try {
      await roomService.deleteRoomType(id);
      toast.success('Room type deleted successfully');
      fetchRoomTypesList();
      fetchRoomTypes(); // Refresh dropdown list
    } catch (error: any) {
      toast.error(error.response?.data?.detail || 'Unable to delete room type');
    }
  };

  const resetRoomTypeForm = () => {
    setEditingRoomType(null);
    setRoomTypeFormData({
      name: '',
      description: '',
      base_price: 0,
      capacity: 1,
      amenities: [],
    });
    setCustomRoomTypeAmenityInput('');
  };

  const toggleRoomTypeAmenity = (amenity: string) => {
    const currentAmenities = roomTypeFormData.amenities || [];
    if (currentAmenities.includes(amenity)) {
      setRoomTypeFormData({
        ...roomTypeFormData,
        amenities: currentAmenities.filter(a => a !== amenity),
      });
    } else {
      setRoomTypeFormData({
        ...roomTypeFormData,
        amenities: [...currentAmenities, amenity],
      });
    }
  };

  const addCustomRoomTypeAmenity = () => {
    if (customRoomTypeAmenityInput.trim() && !roomTypeFormData.amenities?.includes(customRoomTypeAmenityInput.trim())) {
      setRoomTypeFormData({
        ...roomTypeFormData,
        amenities: [...(roomTypeFormData.amenities || []), customRoomTypeAmenityInput.trim()],
      });
      setCustomRoomTypeAmenityInput('');
    }
  };

  const removeRoomTypeAmenity = (amenity: string) => {
    setRoomTypeFormData({
      ...roomTypeFormData,
      amenities: (roomTypeFormData.amenities || []).filter(a => a !== amenity),
    });
  };

  useEffect(() => {
    if (activeTab === 'room-types') {
      fetchRoomTypesList();
    }
  }, [activeTab, fetchRoomTypesList]);

  useEffect(() => {
    let isMounted = true;
    const abortController = new AbortController();

    const fetchData = async () => {
      try {
        await Promise.all([
          fetchAvailableAmenities(),
          fetchRoomTypes(),
        ]);
      } catch (error) {
        if (isMounted && !abortController.signal.aborted) {
          logger.error('Error fetching initial data', error);
        }
      }
    };

    fetchData();

    return () => {
      isMounted = false;
      abortController.abort();
    };
  }, [fetchAvailableAmenities, fetchRoomTypes]);

  // Frontend validation
  const validateRoomForm = (): string | null => {
    if (!roomFormData.room_number.trim()) {
      return 'Room number is required';
    }
    if (roomFormData.floor < 1) {
      return 'Floor must be at least 1';
    }
    if (roomFormData.room_type_id < 1) {
      return 'Room type is required';
    }
    if (roomFormData.price && parseFloat(roomFormData.price) < 0) {
      return 'Price cannot be negative';
    }
    if (roomFormData.capacity && parseInt(roomFormData.capacity) < 1) {
      return 'Capacity must be at least 1';
    }
    return null;
  };

  const handleRoomSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Frontend validation
    const validationError = validateRoomForm();
    if (validationError) {
      toast.error(validationError);
      return;
    }

    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,
          // Don't send amenities - backend will inherit from room type
          amenities: [],
        };
        await contextUpdateRoom(editingRoom.id, updateData);
        
        // Refresh room details for editing
        try {
          const updatedRoom = await roomService.getRoomByNumber(editingRoom.room_number);
          setEditingRoom(updatedRoom.data.room);
        } catch (err) {
          logger.error('Failed to refresh room data', err);
          toast.error('Room updated but failed to refresh details');
        }
      } 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,
          // Don't send amenities - backend will inherit from room type
          amenities: [],
        };
        const response = await roomService.createRoom(createData);
        
        if (response.data?.room) {
          if (selectedFiles.length > 0) {
            // Validate files before upload
            const MAX_FILES = 5;
            const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB per file
            const ALLOWED_TYPES = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'];

            if (selectedFiles.length > MAX_FILES) {
              toast.error(`Maximum ${MAX_FILES} images allowed.`);
              setSelectedFiles([]);
            } else {
              const invalidFiles = selectedFiles.filter(file => 
                !ALLOWED_TYPES.includes(file.type) || file.size > MAX_FILE_SIZE
              );

              if (invalidFiles.length > 0) {
                toast.error('Some files are invalid. Please select valid image files (max 5MB each).');
                setSelectedFiles([]);
              } else {
                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);
                }
              }
            }
          }
          
          // Refresh context to sync the new room - don't call contextCreateRoom as it would duplicate
          await refreshRooms();
          await refreshStatusBoard();
          
          setShowRoomModal(false);
          resetRoomForm();
          toast.success('Room created successfully');
          return;
          
          // Refresh context to sync the new room - don't call contextCreateRoom as it would duplicate
          await refreshRooms();
          await refreshStatusBoard();
          
          setShowRoomModal(false);
          resetRoomForm();
          toast.success('Room created successfully');
          return;
        }
      }
      setShowRoomModal(false);
      resetRoomForm();
      await refreshRooms();
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'An error occurred');
    }
  };

  // Handle edit from status board
  const handleEditRoomFromStatusBoard = async (roomId: number) => {
    try {
      // Find the room in context rooms
      const room = contextRooms.find(r => r.id === roomId);
      if (room) {
        await handleEditRoom(room);
      } else {
        // If not found in context, fetch it
        const response = await roomService.getRoomById(roomId);
        const foundRoom = response.data?.room;
        if (foundRoom) {
          await handleEditRoom(foundRoom);
        } else {
          toast.error('Room not found');
        }
      }
    } catch (error: any) {
      logger.error('Error fetching room for edit', error);
      toast.error('Failed to load room details');
    }
  };

  const handleEditRoom = (room: Room) => {
    navigate(`/admin/rooms/${room.id}/edit`);
  };

  const handleDeleteRoom = async (id: number) => {
    const room = contextRooms.find(r => r.id === id) || statusBoardRooms.find(r => r.id === id);
    const roomNumber = room?.room_number || 'this room';
    
    if (!window.confirm(`Are you sure you want to delete room ${roomNumber}? This action cannot be undone.`)) {
      return;
    }
    
    try {
      await contextDeleteRoom(id);
      toast.success(`Room ${roomNumber} deleted successfully`);
      await refreshStatusBoard();
      await refreshRooms();
      // Remove from expanded rooms if it was expanded
      setExpandedRooms(prev => {
        const newSet = new Set(prev);
        newSet.delete(id);
        return newSet;
      });
    } catch (error: any) {
      toast.error(error.response?.data?.message || error.response?.data?.detail || 'Failed to delete room');
    }
  };

  const resetRoomForm = () => {
    setEditingRoom(null);
    // Get default amenities from first room type if available
    const defaultRoomType = roomTypesList.length > 0 ? roomTypesList[0] : null;
    const defaultAmenities = defaultRoomType ? getAmenitiesArray(defaultRoomType.amenities) : [];
    
    setRoomFormData({
      room_number: '',
      floor: 1,
      room_type_id: roomTypes.length > 0 ? roomTypes[0].id : 1,
      status: 'available',
      featured: false,
      price: '',
      description: '',
      capacity: '',
      room_size: '',
      view: '',
      amenities: defaultAmenities, // Inherit from default room type
    });
    setSelectedFiles([]);
    setUploadingImages(false);
    setCustomAmenityInput('');
    setEditingAmenity(null);
  };

  // Amenities are now managed only at the room type level
  // Rooms automatically inherit amenities from their room type

  const handleAddCustomAmenity = () => {
    const trimmed = customAmenityInput.trim();
    if (trimmed && !roomFormData.amenities.includes(trimmed)) {
      setRoomFormData(prev => ({
        ...prev,
        amenities: [...prev.amenities, trimmed]
      }));
      setCustomAmenityInput('');
    }
  };

  const handleRemoveAmenity = (amenity: string) => {
    setRoomFormData(prev => ({
      ...prev,
      amenities: prev.amenities.filter(a => a !== amenity)
    }));
  };

  const handleEditAmenity = (amenity: string) => {
    setEditingAmenity({ name: amenity, newName: amenity });
  };

  const handleSaveAmenityEdit = async () => {
    if (!editingAmenity || editingAmenity.name === editingAmenity.newName.trim()) {
      setEditingAmenity(null);
      return;
    }

    const newName = editingAmenity.newName.trim();
    if (!newName) {
      toast.error('Amenity name cannot be empty');
      return;
    }

    try {
      await roomService.updateAmenity(editingAmenity.name, newName);
      toast.success(`Amenity "${editingAmenity.name}" updated to "${newName}"`);

      setAvailableAmenities(prev => {
        const updated = prev.map(a => a === editingAmenity.name ? newName : a);
        return updated.sort();
      });

      setRoomFormData(prev => ({
        ...prev,
        amenities: prev.amenities.map(a => a === editingAmenity.name ? newName : a)
      }));

      setEditingAmenity(null);
      await fetchAvailableAmenities();
      await refreshRooms();
      await refreshStatusBoard();
    } catch (error: any) {
      toast.error(error.response?.data?.message || error.response?.data?.detail || 'Failed to update amenity');
    }
  };

  const handleDeleteAmenity = async (amenity: string) => {
    if (!window.confirm(`Are you sure you want to delete "${amenity}"? This will remove it from all rooms and room types.`)) {
      return;
    }

    try {
      await roomService.deleteAmenity(amenity);
      toast.success(`Amenity "${amenity}" deleted successfully`);

      setAvailableAmenities(prev => prev.filter(a => a !== amenity));
      setRoomFormData(prev => ({
        ...prev,
        amenities: prev.amenities.filter(a => a !== amenity)
      }));

      await fetchAvailableAmenities();
      await refreshRooms();
      await refreshStatusBoard();
    } catch (error: any) {
      toast.error(error.response?.data?.message || error.response?.data?.detail || 'Failed to delete amenity');
    }
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files || e.target.files.length === 0) {
      return;
    }

    const files = Array.from(e.target.files);
    const MAX_FILES = 5;
    const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB per file
    const ALLOWED_TYPES = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'];

    // Check file count
    if (files.length > MAX_FILES) {
      toast.error(`Maximum ${MAX_FILES} images allowed. Please select fewer files.`);
      e.target.value = ''; // Reset input
      return;
    }

    // Validate each file
    const validFiles: File[] = [];
    const errors: string[] = [];

    for (let i = 0; i < files.length; i++) {
      const file = files[i];

      // Check file type
      if (!ALLOWED_TYPES.includes(file.type)) {
        errors.push(`${file.name}: Invalid file type. Only JPEG, PNG, WebP, and GIF images are allowed.`);
        continue;
      }

      // Check file size
      if (file.size > MAX_FILE_SIZE) {
        errors.push(`${file.name}: File size exceeds ${MAX_FILE_SIZE / (1024 * 1024)}MB limit.`);
        continue;
      }

      validFiles.push(file);
    }

    // Show errors if any
    if (errors.length > 0) {
      errors.forEach(error => toast.error(error));
    }

    // Set valid files
    if (validFiles.length > 0) {
      setSelectedFiles(validFiles);
      if (validFiles.length < files.length) {
        toast.warning(`${validFiles.length} of ${files.length} files selected. Some files were rejected.`);
      }
    } else {
      setSelectedFiles([]);
      e.target.value = ''; // Reset input if no valid files
    }
  };

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

    // Validate before upload (double-check)
    const MAX_FILES = 5;
    const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB per file
    const ALLOWED_TYPES = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'];

    if (selectedFiles.length > MAX_FILES) {
      toast.error(`Maximum ${MAX_FILES} images allowed.`);
      return;
    }

    // Validate each file one more time before upload
    const invalidFiles = selectedFiles.filter(file => 
      !ALLOWED_TYPES.includes(file.type) || file.size > MAX_FILE_SIZE
    );

    if (invalidFiles.length > 0) {
      toast.error('Some files are invalid. Please select valid image files (max 5MB each).');
      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([]);
      await Promise.all([
        refreshRooms(),
        refreshStatusBoard(),
      ]);
      
      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');
      await Promise.all([
        refreshRooms(),
        refreshStatusBoard(),
      ]);
      
      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 (statusBoardLoading && statusBoardRooms.length === 0 && activeTab === 'status-board') {
    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: 'Rooms & Status Board', icon: Hotel },
            { id: 'room-types' as Tab, label: 'Room Types', icon: Bed },
            { 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">{statusBoardRooms.length}</span> rooms
              </div>
            </div>
            <div className="flex items-center space-x-3">
              <button
                onClick={() => {
                  resetRoomForm();
                  setShowRoomModal(true);
                }}
                className="flex items-center space-x-2 px-5 py-2.5 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-lg hover:from-amber-600 hover:to-amber-700 transition-all duration-200 shadow-md hover:shadow-lg font-medium"
              >
                <Plus className="w-4 h-4" />
                <span>Add Room</span>
              </button>
              <button
                onClick={() => refreshStatusBoard(selectedFloor || undefined)}
                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>
          </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) => {
                        // Determine effective status: if there are pending housekeeping tasks and room is available, show as cleaning
                        const effectiveStatus = room.pending_housekeeping_count > 0 && room.status === 'available' 
                          ? 'cleaning' 
                          : room.status;
                        const statusColors = getStatusColor(effectiveStatus);
                        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]
                              ${expandedRooms.has(room.id) ? 'shadow-lg' : 'shadow-md'}
                            `}
                          >
                            {/* 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 z-20`}>
                              {getStatusIcon(effectiveStatus)}
                              <span>{getStatusLabel(effectiveStatus)}</span>
                            </div>

                            {/* Action Buttons */}
                            <div className="absolute top-3 left-3 flex gap-2 z-20">
                              <button
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleEditRoomFromStatusBoard(room.id);
                                }}
                                className="p-2 bg-white/90 backdrop-blur-sm rounded-lg text-blue-600 hover:text-blue-700 hover:bg-white transition-all duration-200 shadow-md hover:shadow-lg border border-blue-200 hover:border-blue-300"
                                title="Edit Room"
                              >
                                <Edit className="w-4 h-4" />
                              </button>
                              <button
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleDeleteRoom(room.id);
                                }}
                                className="p-2 bg-white/90 backdrop-blur-sm rounded-lg text-rose-600 hover:text-rose-700 hover:bg-white transition-all duration-200 shadow-md hover:shadow-lg border border-rose-200 hover:border-rose-300 hover:scale-105"
                                title={`Delete Room ${room.room_number}`}
                              >
                                <Trash2 className="w-4 h-4" />
                              </button>
                            </div>

                            {/* Room Content */}
                            <div className="p-5 pt-16 cursor-pointer" onClick={() => toggleRoomExpansion(room.id)}>
                              <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 max-h-96 overflow-y-auto 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 flex-shrink-0" />
                                        <span>Guest</span>
                                      </div>
                                      <p className="text-sm font-medium text-slate-900 break-words">{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 flex-shrink-0" />
                                        <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 flex-shrink-0" />
                                        <span>Maintenance</span>
                                      </div>
                                      <p className="text-sm font-medium text-red-900 break-words">{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 flex-shrink-0" />
                                        <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 />}

      {/* Room Types Tab */}
      {activeTab === 'room-types' && (
        <div className="space-y-6">
          <div className="flex justify-between items-center">
            <div>
              <h2 className="text-2xl font-bold text-gray-900">Room Type Management</h2>
              <p className="text-gray-600 mt-1">Manage room types, pricing, and amenities</p>
            </div>
            <button
              onClick={() => {
                resetRoomTypeForm();
                setShowRoomTypeModal(true);
              }}
              className="flex items-center space-x-2 px-5 py-2.5 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-lg hover:from-blue-600 hover:to-blue-700 transition-all duration-200 shadow-md hover:shadow-lg font-medium"
            >
              <Plus className="w-4 h-4" />
              <span>Add Room Type</span>
            </button>
          </div>

          {/* Search Filter */}
          <div className="bg-white rounded-xl p-4 border border-gray-200 shadow-sm">
            <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"
                placeholder="Search room types..."
                value={roomTypeSearchFilter}
                onChange={(e) => setRoomTypeSearchFilter(e.target.value)}
                className="w-full pl-12 pr-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all"
              />
            </div>
          </div>

          {/* Room Types Table */}
          {roomTypesLoading ? (
            <Loading />
          ) : (
            <div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="bg-gradient-to-r from-gray-800 to-gray-900">
                      <th className="px-6 py-4 text-left text-xs font-bold text-white uppercase tracking-wider">Name</th>
                      <th className="px-6 py-4 text-left text-xs font-bold text-white uppercase tracking-wider">Description</th>
                      <th className="px-6 py-4 text-left text-xs font-bold text-white uppercase tracking-wider">Base Price</th>
                      <th className="px-6 py-4 text-left text-xs font-bold text-white uppercase tracking-wider">Capacity</th>
                      <th className="px-6 py-4 text-left text-xs font-bold text-white uppercase tracking-wider">Amenities</th>
                      <th className="px-6 py-4 text-right text-xs font-bold text-white uppercase tracking-wider">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {roomTypesList
                      .filter(rt =>
                        rt.name.toLowerCase().includes(roomTypeSearchFilter.toLowerCase()) ||
                        (rt.description && rt.description.toLowerCase().includes(roomTypeSearchFilter.toLowerCase()))
                      )
                      .map((roomType) => {
                        const amenities = getAmenitiesArray(roomType.amenities);
                        return (
                          <tr key={roomType.id} className="hover:bg-gray-50 transition-colors">
                            <td className="px-6 py-4 whitespace-nowrap">
                              <div className="flex items-center gap-3">
                                <div className="p-2 bg-blue-100 rounded-lg">
                                  <Bed className="w-4 h-4 text-blue-600" />
                                </div>
                                <span className="text-sm font-semibold text-gray-900">{roomType.name}</span>
                              </div>
                            </td>
                            <td className="px-6 py-4">
                              <div className="text-sm text-gray-600 max-w-md">
                                {roomType.description || <span className="text-gray-400 italic">No description</span>}
                              </div>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <div className="text-sm font-bold text-emerald-600">
                                {formatCurrency(roomType.base_price)}
                              </div>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <div className="text-sm font-semibold text-gray-700">
                                {roomType.capacity} {roomType.capacity === 1 ? 'guest' : 'guests'}
                              </div>
                            </td>
                            <td className="px-6 py-4">
                              <div className="flex flex-wrap gap-1 max-w-md">
                                {amenities.slice(0, 3).map((amenity, idx) => (
                                  <span
                                    key={idx}
                                    className="px-2 py-1 text-xs font-medium bg-blue-100 text-blue-800 rounded-md"
                                  >
                                    {amenity}
                                  </span>
                                ))}
                                {amenities.length > 3 && (
                                  <span className="px-2 py-1 text-xs font-medium bg-gray-100 text-gray-600 rounded-md">
                                    +{amenities.length - 3} more
                                  </span>
                                )}
                                {amenities.length === 0 && (
                                  <span className="text-xs text-gray-400 italic">No amenities</span>
                                )}
                              </div>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-right">
                              <div className="flex items-center justify-end gap-2">
                                <button
                                  onClick={() => handleRoomTypeEdit(roomType)}
                                  className="p-2 rounded-lg text-blue-600 hover:text-blue-700 hover:bg-blue-50 transition-all"
                                  title="Edit"
                                >
                                  <Edit className="w-5 h-5" />
                                </button>
                                <button
                                  onClick={() => handleRoomTypeDelete(roomType.id)}
                                  className="p-2 rounded-lg text-rose-600 hover:text-rose-700 hover:bg-rose-50 transition-all"
                                  title="Delete"
                                >
                                  <Trash2 className="w-5 h-5" />
                                </button>
                              </div>
                            </td>
                          </tr>
                        );
                      })}
                  </tbody>
                </table>
                {roomTypesList.filter(rt =>
                  rt.name.toLowerCase().includes(roomTypeSearchFilter.toLowerCase()) ||
                  (rt.description && rt.description.toLowerCase().includes(roomTypeSearchFilter.toLowerCase()))
                ).length === 0 && (
                  <div className="text-center py-12">
                    <Bed className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                    <p className="text-gray-500">No room types found</p>
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      )}

      {/* Room Modal */}
      {showRoomModal && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center z-[100] 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) => {
                      const selectedRoomTypeId = parseInt(e.target.value);
                      // Find the selected room type and inherit its amenities
                      const selectedRoomType = roomTypesList.find(rt => rt.id === selectedRoomTypeId);
                      const inheritedAmenities = selectedRoomType ? getAmenitiesArray(selectedRoomType.amenities) : [];
                      setRoomFormData({ 
                        ...roomFormData, 
                        room_type_id: selectedRoomTypeId,
                        amenities: inheritedAmenities // Inherit amenities from room type
                      });
                    }}
                    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>
                  <p className="text-xs text-gray-400 mt-1 italic">
                    Amenities are inherited from the selected room type. Manage amenities in the Room Types tab.
                  </p>
                </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 'available' | 'occupied' | 'maintenance' })}
                    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 bg-[#0a0a0a]/50 backdrop-blur-sm">
                  {(() => {
                    const selectedRoomType = roomTypesList.find(rt => rt.id === roomFormData.room_type_id);
                    const inheritedAmenities = selectedRoomType ? getAmenitiesArray(selectedRoomType.amenities) : [];
                    
                    if (inheritedAmenities.length === 0) {
                      return (
                        <div className="text-center py-6">
                          <p className="text-sm text-gray-400 mb-2">No amenities defined for this room type.</p>
                          <p className="text-xs text-gray-500 italic">
                            Go to the <strong>Room Types</strong> tab to add amenities to this room type.
                          </p>
                        </div>
                      );
                    }
                    
                    return (
                      <>
                        <div className="mb-3">
                          <p className="text-xs text-gray-400 italic flex items-center gap-2">
                            <Check className="w-3 h-3 text-[#d4af37]" />
                            Inherited from room type: <strong className="text-[#d4af37]">{selectedRoomType?.name}</strong>
                          </p>
                        </div>
                        <div className="flex flex-wrap gap-2">
                          {inheritedAmenities.map((amenity) => (
                            <span
                              key={amenity}
                              className="px-3 py-1.5 bg-gradient-to-r from-[#d4af37]/20 to-[#c9a227]/20 border border-[#d4af37]/30 rounded-lg text-sm text-[#d4af37] font-medium"
                            >
                              {amenity}
                            </span>
                          ))}
                        </div>
                        <p className="text-xs text-gray-500 mt-3 italic">
                          To modify amenities, edit the room type in the <strong>Room Types</strong> tab.
                        </p>
                      </>
                    );
                  })()}
                </div>
              </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, 5MB each):
                  </label>
                  <div className="flex gap-4">
                    <div className="flex-1">
                      <input
                        type="file"
                        accept="image/jpeg,image/jpg,image/png,image/webp,image/gif"
                        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"
                      />
                      <p className="text-xs text-gray-500 mt-1 italic">
                        Accepted formats: JPEG, PNG, WebP, GIF. Maximum 5MB per file.
                      </p>
                    </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
                        {selectedFiles.length > 0 && (
                          <span className="ml-2 text-xs">
                            (Total: {(selectedFiles.reduce((sum, f) => sum + f.size, 0) / (1024 * 1024)).toFixed(2)}MB)
                          </span>
                        )}
                      </p>
                      <button
                        type="button"
                        onClick={handleUploadImages}
                        disabled={uploadingImages || selectedFiles.length === 0}
                        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>
      )}

      {/* Room Type Modal */}
      {showRoomTypeModal && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
            <div className="sticky top-0 bg-gradient-to-r from-blue-500 to-blue-600 px-8 py-6 flex justify-between items-center rounded-t-2xl">
              <h2 className="text-2xl font-bold text-white">
                {editingRoomType ? 'Edit Room Type' : 'Create Room Type'}
              </h2>
              <button
                onClick={() => {
                  setShowRoomTypeModal(false);
                  resetRoomTypeForm();
                }}
                className="p-2 rounded-lg text-white hover:bg-white/20 transition-colors"
              >
                <X className="w-6 h-6" />
              </button>
            </div>

            <form onSubmit={handleRoomTypeSubmit} className="p-8 space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">Name *</label>
                  <input
                    type="text"
                    required
                    value={roomTypeFormData.name}
                    onChange={(e) => setRoomTypeFormData({ ...roomTypeFormData, name: e.target.value })}
                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">Base Price *</label>
                  <input
                    type="number"
                    required
                    step="0.01"
                    min="0"
                    value={roomTypeFormData.base_price}
                    onChange={(e) => setRoomTypeFormData({ ...roomTypeFormData, base_price: parseFloat(e.target.value) || 0 })}
                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">Capacity *</label>
                  <input
                    type="number"
                    required
                    min="1"
                    max="20"
                    value={roomTypeFormData.capacity}
                    onChange={(e) => setRoomTypeFormData({ ...roomTypeFormData, capacity: parseInt(e.target.value) || 1 })}
                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all"
                  />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-semibold text-gray-700 mb-2">Description</label>
                  <textarea
                    value={roomTypeFormData.description}
                    onChange={(e) => setRoomTypeFormData({ ...roomTypeFormData, description: e.target.value })}
                    rows={3}
                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all"
                  />
                </div>
              </div>

              <div className="border-t border-gray-200 pt-6">
                <h3 className="text-lg font-semibold text-gray-900 mb-4">Amenities</h3>
                
                {/* Available Amenities */}
                {availableAmenities.length > 0 && (
                  <div className="mb-4">
                    <label className="block text-sm font-semibold text-gray-700 mb-2">Select Amenities</label>
                    <div className="flex flex-wrap gap-2">
                      {availableAmenities.map((amenity) => (
                        <button
                          key={amenity}
                          type="button"
                          onClick={() => toggleRoomTypeAmenity(amenity)}
                          className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
                            roomTypeFormData.amenities?.includes(amenity)
                              ? 'bg-blue-500 text-white shadow-md'
                              : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                          }`}
                        >
                          {amenity}
                        </button>
                      ))}
                    </div>
                  </div>
                )}

                {/* Custom Amenity Input */}
                <div className="mb-4">
                  <label className="block text-sm font-semibold text-gray-700 mb-2">Add Custom Amenity</label>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={customRoomTypeAmenityInput}
                      onChange={(e) => setCustomRoomTypeAmenityInput(e.target.value)}
                      onKeyPress={(e) => {
                        if (e.key === 'Enter') {
                          e.preventDefault();
                          addCustomRoomTypeAmenity();
                        }
                      }}
                      placeholder="Enter amenity name..."
                      className="flex-1 px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all"
                    />
                    <button
                      type="button"
                      onClick={addCustomRoomTypeAmenity}
                      className="px-6 py-3 bg-blue-500 text-white rounded-xl font-semibold hover:bg-blue-600 transition-all"
                    >
                      Add
                    </button>
                  </div>
                </div>

                {/* Selected Amenities */}
                {(roomTypeFormData.amenities || []).length > 0 && (
                  <div>
                    <label className="block text-sm font-semibold text-gray-700 mb-2">Selected Amenities</label>
                    <div className="flex flex-wrap gap-2">
                      {(roomTypeFormData.amenities || []).map((amenity, idx) => (
                        <span
                          key={idx}
                          className="inline-flex items-center gap-2 px-4 py-2 bg-blue-100 text-blue-800 rounded-lg text-sm font-medium"
                        >
                          {amenity}
                          <button
                            type="button"
                            onClick={() => removeRoomTypeAmenity(amenity)}
                            className="text-blue-600 hover:text-blue-800"
                          >
                            <X className="w-4 h-4" />
                          </button>
                        </span>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              <div className="flex justify-end gap-4 pt-6 border-t border-gray-200">
                <button
                  type="button"
                  onClick={() => {
                    setShowRoomTypeModal(false);
                    resetRoomTypeForm();
                  }}
                  className="px-6 py-3 border-2 border-gray-300 text-gray-700 rounded-xl font-semibold hover:bg-gray-50 transition-all"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-6 py-3 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-xl font-semibold hover:from-blue-600 hover:to-blue-700 transition-all shadow-lg hover:shadow-xl"
                >
                  {editingRoomType ? 'Update Room Type' : 'Create Room Type'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default AdvancedRoomManagementPage;

