import React, { useState, useEffect, useMemo, useRef } from 'react';
import {
  Hotel,
  Wrench,
  Sparkles,
  ClipboardCheck,
  Filter,
  RefreshCw,
  CheckCircle,
  AlertTriangle,
  Users,
  ChevronDown,
  ChevronUp,
  Calendar,
  MapPin,
} from 'lucide-react';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import { logger } from '../../shared/utils/logger';
import advancedRoomService, {
  RoomStatusBoardItem,
} from '../../features/rooms/services/advancedRoomService';
import roomService 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';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

export default AdvancedRoomManagementPage;

