import React, { useEffect, useState } from 'react';
import { Plus, Search, Edit, Trash2, X, Upload, Image as ImageIcon, Check } from 'lucide-react';
import { roomService, Room } from '../../services/api';
import { toast } from 'react-toastify';
import Loading from '../../components/common/Loading';
import Pagination from '../../components/common/Pagination';
import apiClient from '../../services/api/apiClient';
import { useFormatCurrency } from '../../hooks/useFormatCurrency';

const RoomManagementPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const [rooms, setRooms] = useState<Room[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editingRoom, setEditingRoom] = useState<Room | null>(null);
  const [selectedRooms, setSelectedRooms] = useState<number[]>([]);
  const [filters, setFilters] = useState({
    search: '',
    status: '',
    type: '',
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const itemsPerPage = 5;

  const [formData, setFormData] = 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(() => {
    setCurrentPage(1);
    setSelectedRooms([]);
  }, [filters]);

  useEffect(() => {
    fetchRooms();
    fetchAvailableAmenities();
  }, [filters, currentPage]);
  
  
  useEffect(() => {
    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) {
              
              console.error(`Failed to fetch page ${page}:`, err);
            }
          }
        }
        
        if (allUniqueRoomTypes.size > 0) {
          const roomTypesList = Array.from(allUniqueRoomTypes.values());
          setRoomTypes(roomTypesList);
          
          if (!editingRoom && formData.room_type_id === 1 && roomTypesList.length > 0) {
            setFormData(prev => ({ ...prev, room_type_id: roomTypesList[0].id }));
          }
        }
      } catch (err) {
        console.error('Failed to fetch room types:', err);
      }
    };
    fetchAllRoomTypes();
  }, []);

  const fetchAvailableAmenities = async () => {
    try {
      const response = await roomService.getAmenities();
      if (response.data?.amenities) {
        setAvailableAmenities(response.data.amenities);
      }
    } catch (error) {
      console.error('Failed to fetch amenities:', error);
    }
  };

  const fetchRooms = async () => {
    try {
      setLoading(true);
      const response = await roomService.getRooms({
        ...filters,
        page: currentPage,
        limit: itemsPerPage,
      });
      setRooms(response.data.rooms);
      if (response.data.pagination) {
        setTotalPages(response.data.pagination.totalPages);
        setTotalItems(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()));
      
      
      if (roomTypes.length === 0 && response.data.pagination) {
        try {
          
          const allRoomsResponse = await roomService.getRooms({ limit: 100, page: 1 });
          const allUniqueRoomTypes = new Map<number, { id: number; name: string }>();
          allRoomsResponse.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 (allRoomsResponse.data.pagination && allRoomsResponse.data.pagination.totalPages > 1) {
            const totalPages = allRoomsResponse.data.pagination.totalPages;
            for (let page = 2; page <= Math.min(totalPages, 10); 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) {
                
              }
            }
          }
          
          if (allUniqueRoomTypes.size > 0) {
            setRoomTypes(Array.from(allUniqueRoomTypes.values()));
          }
        } catch (err) {
          
        }
      }
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Unable to load rooms list');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingRoom) {
        
        const updateData = {
          ...formData,
          price: formData.price ? parseFloat(formData.price) : undefined,
          description: formData.description || undefined,
          capacity: formData.capacity ? parseInt(formData.capacity) : undefined,
          room_size: formData.room_size || undefined,
          view: formData.view || undefined,
          amenities: Array.isArray(formData.amenities) ? formData.amenities : [],
        };
        await roomService.updateRoom(editingRoom.id, updateData);
        toast.success('Room updated successfully');
        
        
        await fetchRooms();
        
        
        try {
          const updatedRoom = await roomService.getRoomByNumber(editingRoom.room_number);
          setEditingRoom(updatedRoom.data.room);
        } catch (err) {
          console.error('Failed to refresh room data:', err);
        }
      } else {
        
        const createData = {
          ...formData,
          price: formData.price ? parseFloat(formData.price) : undefined,
          description: formData.description || undefined,
          capacity: formData.capacity ? parseInt(formData.capacity) : undefined,
          room_size: formData.room_size || undefined,
          view: formData.view || undefined,
          amenities: Array.isArray(formData.amenities) ? formData.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);
          }
          
          
          setFormData({
            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 fetchRooms();
          
          return;
        }
      }
      
      setShowModal(false);
      resetForm();
      fetchRooms();
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'An error occurred');
    }
  };

  const handleEdit = async (room: Room) => {
    setEditingRoom(room);
    
    
    let amenitiesArray: string[] = [];
    const roomAmenities = room.amenities as string[] | string | undefined;
    if (roomAmenities) {
      if (Array.isArray(roomAmenities)) {
        amenitiesArray = roomAmenities;
      } else if (typeof roomAmenities === 'string') {
        try {
          const parsed = JSON.parse(roomAmenities);
          amenitiesArray = Array.isArray(parsed) ? parsed : [];
        } catch {
          amenitiesArray = roomAmenities.split(',').map((a: string) => a.trim()).filter(Boolean);
        }
      }
    }
    
    
    setFormData({
      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,
    });
    
    setShowModal(true);
    
    
    try {
      const fullRoom = await roomService.getRoomByNumber(room.room_number);
      const roomData = fullRoom.data.room;
      
      
      let updatedAmenitiesArray: string[] = [];
      const roomDataAmenities = roomData.amenities as string[] | string | undefined;
      if (roomDataAmenities) {
        if (Array.isArray(roomDataAmenities)) {
          updatedAmenitiesArray = roomDataAmenities;
        } else if (typeof roomDataAmenities === 'string') {
          try {
            const parsed = JSON.parse(roomDataAmenities);
            updatedAmenitiesArray = Array.isArray(parsed) ? parsed : [];
          } catch {
            
            updatedAmenitiesArray = roomDataAmenities.split(',').map((a: string) => a.trim()).filter(Boolean);
          }
        }
      }
      
      
      setFormData({
        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) {
      console.error('Failed to fetch full room details:', error);
      
    }
  };

  const handleDelete = 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));
      fetchRooms();
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Unable to delete room');
    }
  };

  const handleBulkDelete = 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([]);
      fetchRooms();
    } 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 handleSelectAll = () => {
    if (selectedRooms.length === rooms.length) {
      setSelectedRooms([]);
    } else {
      setSelectedRooms(rooms.map(room => room.id));
    }
  };

  const resetForm = () => {
    setEditingRoom(null);
    setFormData({
      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) => {
    setFormData(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([]);
      fetchRooms();
      
      
      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');
      fetchRooms();
      
      
      const response = await roomService.getRoomByNumber(editingRoom.room_number);
      setEditingRoom(response.data.room);
    } catch (error: any) {
      console.error('Error deleting image:', error);
      toast.error(error.response?.data?.message || error.response?.data?.detail || 'Unable to delete image');
    }
  };

  const getStatusBadge = (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) {
    return <Loading />;
  }

  return (
    <div className="space-y-8 bg-gradient-to-br from-slate-50 via-white to-slate-50 min-h-screen -m-6 p-8">
      {}
      <div className="flex justify-between items-center animate-fade-in">
        <div>
          <div className="flex items-center gap-3 mb-2">
            <div className="h-1 w-16 bg-gradient-to-r from-amber-400 to-amber-600 rounded-full"></div>
            <h1 className="text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
              Room Management
            </h1>
          </div>
          <p className="text-slate-600 mt-3 text-lg font-light">Manage hotel room information</p>
        </div>
        <div className="flex gap-3">
          {selectedRooms.length > 0 && (
            <button
              onClick={handleBulkDelete}
              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={() => {
              resetForm();
              setShowModal(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 className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 p-6 animate-fade-in" style={{ animationDelay: '0.1s' }}>
        <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-slate-400 w-5 h-5 group-focus-within:text-amber-500 transition-colors" />
            <input
              type="text"
              placeholder="Search rooms..."
              value={filters.search}
              onChange={(e) => setFilters({ ...filters, search: e.target.value })}
              className="w-full pl-12 pr-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 placeholder-slate-400 font-medium shadow-sm hover:shadow-md"
            />
          </div>
          <select
            value={filters.status}
            onChange={(e) => setFilters({ ...filters, status: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-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={filters.type}
            onChange={(e) => setFilters({ ...filters, type: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-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/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 overflow-hidden animate-fade-in" style={{ animationDelay: '0.2s' }}>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900">
                <th className="px-8 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={rooms.length > 0 && selectedRooms.length === rooms.length}
                    onChange={handleSelectAll}
                    title="Select all rooms"
                    className="w-5 h-5 text-amber-600 bg-slate-700 border-slate-600 rounded focus:ring-amber-500 cursor-pointer"
                  />
                </th>
                <th className="px-8 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-8 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-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">
                  Floor
                </th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">
                  Price
                </th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">
                  Status
                </th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">
                  Featured
                </th>
                <th className="px-8 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">
              {rooms.map((room, index) => (
                <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' : ''}`}
                  style={{ animationDelay: `${index * 0.05}s` }}
                >
                  <td className="px-8 py-5 whitespace-nowrap">
                    <input
                      type="checkbox"
                      checked={selectedRooms.includes(room.id)}
                      onChange={() => handleSelectRoom(room.id)}
                      className="w-5 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-8 py-5 whitespace-nowrap">
                    <div className="text-sm font-bold text-slate-900 font-mono">{room.room_number}</div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="text-sm font-medium text-slate-900">{room.room_type?.name || 'N/A'}</div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="text-sm text-slate-700">Floor {room.floor}</div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="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-8 py-5 whitespace-nowrap">
                    {getStatusBadge(room.status)}
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    {room.featured ? (
                      <span className="text-amber-500 text-lg">⭐</span>
                    ) : (
                      <span className="text-slate-400">-</span>
                    )}
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap text-right">
                    <div className="flex items-center justify-end gap-2">
                      <button
                        onClick={() => handleEdit(room)}
                        className="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-5 h-5" />
                      </button>
                      <button
                        onClick={() => handleDelete(room.id)}
                        className="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-5 h-5" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {}
      <Pagination
        currentPage={currentPage}
        totalPages={totalPages}
        onPageChange={setCurrentPage}
        totalItems={totalItems}
        itemsPerPage={itemsPerPage}
      />

      {}
      {showModal && (
        <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 custom-scrollbar">
            
            {}
            <div className="flex justify-between items-center mb-6 pb-6 border-b border-[#d4af37]/20">
              <div>
                <h2 className="text-3xl 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={() => setShowModal(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={handleSubmit} 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={formData.room_number}
                      onChange={(e) => setFormData({ ...formData, 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={formData.floor}
                      onChange={(e) => setFormData({ ...formData, 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={formData.room_type_id}
                    onChange={(e) => setFormData({ ...formData, 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={formData.status}
                    onChange={(e) => setFormData({ ...formData, 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={formData.featured}
                    onChange={(e) => setFormData({ ...formData, 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={formData.price}
                    onChange={(e) => setFormData({ ...formData, 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"
                  />
                  <p className="text-xs text-gray-400 mt-1 font-light">
                    This is the actual price for this room. If left empty, the room type base price will be used as a fallback.
                  </p>
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-300 mb-2">
                    Room Description
                  </label>
                  <textarea
                    value={formData.description}
                    onChange={(e) => setFormData({ ...formData, 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..."
                  />
                  <p className="text-xs text-gray-400 mt-1 font-light">
                    This is the actual description shown for this room. If left empty, the room type description will be used as a fallback.
                  </p>
                </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={formData.capacity}
                      onChange={(e) => setFormData({ ...formData, 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"
                    />
                    <p className="text-xs text-gray-400 mt-1 font-light">
                      Room-specific capacity. If left empty, room type capacity will be used.
                    </p>
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      Room Size
                    </label>
                    <input
                      type="text"
                      value={formData.room_size}
                      onChange={(e) => setFormData({ ...formData, 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"
                    />
                    <p className="text-xs text-gray-400 mt-1 font-light">
                      Room size information (e.g., "1 Room", "50 sqm")
                    </p>
                  </div>
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-300 mb-2">
                    View
                  </label>
                  <input
                    type="text"
                    value={formData.view}
                    onChange={(e) => setFormData({ ...formData, 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"
                  />
                  <p className="text-xs text-gray-400 mt-1 font-light">
                    The view from this room (e.g., "City View", "Ocean View")
                  </p>
                </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 custom-scrollbar">
                  {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 = formData.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>
                {formData.amenities.length > 0 && (
                  <p className="text-xs text-gray-400 font-light italic">
                    {formData.amenities.length} amenit{formData.amenities.length === 1 ? 'y' : 'ies'} selected
                  </p>
                )}
              </div>

              {}
              {!editingRoom && (
                <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]" />
                    <ImageIcon className="w-5 h-5" />
                    Room Images (Optional)
                  </h3>
                  <div className="space-y-4">
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      Select Images (will be uploaded after room is created):
                    </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 && (
                      <p className="text-sm text-gray-400 font-light italic">
                        {selectedFiles.length} file(s) selected
                      </p>
                    )}
                  </div>
                </div>
              )}
              
              <div className="flex gap-4 pt-4 border-t border-[#d4af37]/20">
                <button
                  type="button"
                  onClick={() => setShowModal(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>
                
                {}
                {(() => {
                  if (!editingRoom) return null;
                  
                  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: string) => {
                      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>
                    <button
                      type="button"
                      onClick={handleUploadImages}
                      disabled={selectedFiles.length === 0 || uploadingImages}
                      className="px-6 py-3 bg-gradient-to-r from-green-600 to-green-700 
                        text-white rounded-lg hover:from-green-500 hover:to-green-600 
                        disabled:from-gray-600 disabled:to-gray-700 disabled:cursor-not-allowed 
                        flex items-center gap-2 font-semibold shadow-lg shadow-green-600/30
                        hover:shadow-xl hover:shadow-green-600/40 transition-all duration-300"
                    >
                      <Upload className="w-4 h-4" />
                      {uploadingImages ? 'Uploading...' : 'Upload'}
                    </button>
                  </div>
                  {selectedFiles.length > 0 && (
                    <p className="text-sm text-gray-400 font-light italic">
                      {selectedFiles.length} file(s) selected
                    </p>
                  )}
                </div>
              </div>
            )}

          </div>
        </div>
      )}
    </div>
  );
};

export default RoomManagementPage;
