import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:smart_hotel_app/views/service/index/cubit/service_index_cubit.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/routes/app_router.gr.dart';
import 'package:smart_hotel_app/views/service/index/cubit/service_index_state.dart';
import 'package:smart_hotel_app/views/service/index/widget/area_device_list.dart';
import 'package:smart_hotel_app/utils/toast_utils.dart';

class RoomManagementBlock extends StatefulWidget {
  const RoomManagementBlock({super.key});

  @override
  State<RoomManagementBlock> createState() => _RoomManagementBlockState();
}

class _RoomManagementBlockState extends State<RoomManagementBlock> {
  String? _selectedFloor;
  String? _selectedType;
  String? _selectedRoom;
  int? _selectedRoomId;
  String _searchText = '';
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _scrollController = ScrollController();

  List<Map<String, dynamic>> _getFilteredRooms(ServiceIndexCubit cubit) {
    List<Map<String, dynamic>> allRooms;
    if (_selectedFloor == null) {
      allRooms = [];
      for (final floorMap in (cubit.state.floors ?? [])) {
        final floorName = floorMap.values.first;
        allRooms.addAll(cubit.getRoomsByFloor(floorName));
      }
    } else {
      allRooms = cubit.getRoomsByFloor(_selectedFloor!);
    }

    if (_selectedType != null) {
      allRooms = allRooms
          .where((room) => room['type'] == _selectedType)
          .toList();
    }

    if (_searchText.isEmpty) {
      return allRooms;
    }
    final filtered = allRooms
        .where((room) =>
            (room['number'] as String).toLowerCase().contains(_searchText.toLowerCase()))
        .toList();
    return filtered;
  }

  /// 加载非客房区域设备
  void _loadAreaDevices(ServiceIndexCubit cubit) {
    if (_selectedFloor == null) return;
    // 从 floors 中找对应 floorId
    int? floorId;
    for (final floorMap in (cubit.state.floors ?? [])) {
      if (floorMap.values.first == _selectedFloor) {
        floorId = floorMap.keys.first;
        break;
      }
    }
    if (floorId == null) return;
    cubit.loadAreaDevices(floorId: floorId, areaType: _selectedType!);
  }

  @override
  Widget build(BuildContext context) {
    final cubit = context.read<ServiceIndexCubit>();
    return BlocListener<ServiceIndexCubit, ServiceIndexState>(
      listener: (context, state) {
        if (_selectedFloor != state.selectedFloor) {
          setState(() {
            _selectedFloor = state.selectedFloor;
          });
        }
      },
      child: Container(
      width: double.infinity,
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(24.r),
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: const Color.fromRGBO(0, 0, 0, 0.03),
            blurRadius: 20.r,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildFloorSelector(cubit),
          SizedBox(height: 18.h),
          _buildTypeSelector(),
          SizedBox(height: 18.h),
          if (_selectedType == null || _selectedType == '客房') ...[
            _buildSearchBox(),
            SizedBox(height: 32.h),
            _buildLine(),
            SizedBox(height: 18.h),
            _buildRoomGrid(cubit),
            SizedBox(height: 20.h),
            if (_selectedRoom != null)
              Padding(
                padding: EdgeInsets.only(bottom: 15.h),
                child: Text(
                  '已选：$_selectedRoom号房',
                  style: TextStyle(
                    fontSize: 24.sp,
                    color: const Color.fromRGBO(100, 116, 139, 1),
                  ),
                ),
              ),
            BlocBuilder<ServiceIndexCubit, ServiceIndexState>(
              builder: (context, state) => _buildBottomButtons(cubit),
            ),
          ] else ...[
            _buildLine(),
            SizedBox(height: 18.h),
            BlocBuilder<ServiceIndexCubit, ServiceIndexState>(
              builder: (context, state) => AreaDeviceList(
                devices: state.areaDevices,
                isLoading: state.isLoadingAreaDevices,
              ),
            ),
          ],
          
        ],
      ),
    ),
    );
  }

  Widget _buildFloorSelector(ServiceIndexCubit cubit) {
    final floors = cubit.state.floors;
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: (floors ?? []).map((floorMap) {
          final floorName = floorMap.values.first;
          final floorId = floorMap.keys.first;
          final isSelected = _selectedFloor == floorName;
          final displayFloor = floorName;
          return Padding(
            padding: EdgeInsets.only(right: 24.w),
            child: GestureDetector(
              onTap: () {
                setState(() {
                  if (_selectedFloor == floorName) {
                    _selectedFloor = null;
                  } else {
                    _selectedFloor = floorName;
                  }
                  _selectedType = null;
                  _searchController.clear();
                  _searchText = '';
                });
                // 切换楼层时重新请求接口
                if (_selectedFloor != null) {
                  cubit.selectFloor(_selectedFloor);
                  cubit.loadRooms(floorId: floorId);
                }
              },
              child: Column(
                children: [
                  Text(
                    '$displayFloor楼',
                    style: TextStyle(
                      fontSize: 28.sp,
                      color: isSelected
                          ? const Color.fromRGBO(80, 162, 255, 1)
                          : const Color.fromRGBO(0, 0, 0, 1),
                      fontWeight:
                          isSelected ? FontWeight.bold : FontWeight.normal,
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Container(
                    width: 50.w,
                    height: 3.h,
                    decoration: BoxDecoration(
                      color: isSelected
                          ? const Color.fromRGBO(80, 162, 255, 1)
                          : Colors.transparent,
                      borderRadius: BorderRadius.circular(2.r),
                    ),
                  ),
                ],
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildTypeSelector() {
    final cubit = context.read<ServiceIndexCubit>();
    final types = cubit.state.areas.isNotEmpty
        ? cubit.state.areas
        : [];
    return Row(
      children: types.asMap().entries.map((entry) {
        final index = entry.key;
        final type = entry.value;
        final isSelected = _selectedType == type;
        return Container(
          width: 100.w,
          child: Padding(
            padding:
                EdgeInsets.only(right: index < types.length - 1 ? 10.w : 0),
            child: GestureDetector(
              onTap: () {
                setState(() {
                  if (_selectedType == type) {
                    _selectedType = null;
                  } else {
                    _selectedType = type;
                  }
                  _selectedRoom = null;
                  _selectedRoomId = null;
                });
                // 非客房类型时，加载区域设备数据
                if (_selectedType != null && _selectedType != '客房') {
                  _loadAreaDevices(cubit);
                }
              },
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 8.h),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8.r),
                  border: Border.all(
                    color: isSelected
                        ? const Color.fromRGBO(73, 149, 234, 0.5)
                        : Colors.transparent,
                    width: 1.w,
                  ),
                  color: isSelected
                      ? const Color.fromRGBO(73, 149, 234, 0.2)
                      : const Color.fromRGBO(238, 238, 238, 1),
                ),
                child: Center(
                  child: Text(
                    type,
                    style: TextStyle(
                      fontSize: 24.sp,
                      color: isSelected
                          ? const Color.fromRGBO(73, 149, 234, 1)
                          : const Color.fromRGBO(100, 116, 139, 1),
                      fontWeight:
                          isSelected ? FontWeight.bold : FontWeight.normal,
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      }).toList(),
    );
  }

  Widget _buildSearchBox() {
    return Container(
      height: 80.h,
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(86.r),
        color: Colors.white,
        border: Border.all(
          color: const Color.fromRGBO(146, 191, 243, 1),
          width: 1.w,
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.search,
            color: const Color.fromRGBO(153, 153, 153, 1),
            size: 37.sp,
          ),
          SizedBox(width: 26.w),
          Expanded(
            child: TextField(
              controller: _searchController,
              onChanged: (value) {
                setState(() {
                  _searchText = value;
                });
              },
              style: TextStyle(
                fontSize: 24.sp,
                color: const Color.fromRGBO(100, 116, 139, 1),
              ),
              decoration: InputDecoration(
                hintText: '输入房号快速查找，如301...',
                hintStyle: TextStyle(
                  fontSize: 24.sp,
                  color: const Color.fromRGBO(100, 116, 139, 1),
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(vertical: 16.h),
                isCollapsed: true,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLine() {
    return Container(
      height: 1.h,
      color: const Color.fromRGBO(100, 116, 139, 1),
    );
  }

  String _buildFilterLabel() {
    final floorPart = _selectedFloor?.replaceAll('楼', '') ?? '';
    return floorPart.isNotEmpty ? '客房${floorPart}楼·左右滑动选择' : '左右滑动选择';
  }

  Widget _buildRoomGrid(ServiceIndexCubit cubit) {
    final filteredRooms = _getFilteredRooms(cubit);
    const crossAxisCount = 12;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              _buildFilterLabel(),
              style: TextStyle(
                fontSize: 24.sp,
                color: const Color.fromRGBO(100, 116, 139, 1),
              ),
            ),
            Text(
              '共${filteredRooms.length}间',
              style: TextStyle(
                fontSize: 24.sp,
                color: const Color.fromRGBO(73, 149, 234, 1),
              ),
            ),
          ],
        ),
        SizedBox(height: 10.h),
        if (filteredRooms.isEmpty)
          Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(vertical: 40.h),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(15.r),
              color: const Color.fromRGBO(245, 245, 245, 1),
            ),
            child: Center(
              child: Text(
                '未找到匹配的房间',
                style: TextStyle(
                  fontSize: 15.sp,
                  color: const Color.fromRGBO(153, 153, 153, 1),
                ),
              ),
            ),
          )
        else
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            controller: _scrollController,
            child: SizedBox(
              width: (120.w + 12.w) * crossAxisCount,
              child: GridView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                padding: EdgeInsets.zero,
                gridDelegate:
                    const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: crossAxisCount,
                  crossAxisSpacing: 12,
                  mainAxisSpacing: 12,
                  childAspectRatio: 1,
                ),
                itemCount: filteredRooms.length,
                itemBuilder: (context, index) {
                  final room = filteredRooms[index];
                  final isSelected = _selectedRoom == room['number'];
                  return _buildRoomItem(room, isSelected);
                },
              ),
            ),
          ),
      ],
    );
  }

  Widget _buildRoomItem(Map<String, dynamic> room, bool isSelected) {
    final status = room['status'] as String;
    Color backgroundColor;
    Color borderColor;
    Color textColor;
    Color statusTextColor;
    switch (status) {
      case '入住':
        backgroundColor = const Color.fromRGBO(220, 236, 255, 1);
        borderColor = isSelected
            ? const Color.fromRGBO(64, 158, 255, 1)
            : Colors.transparent;
        textColor = const Color.fromRGBO(100, 116, 139, 1);
        statusTextColor = const Color.fromRGBO(73, 149, 234, 1);
        break;
      case '待清洁':
        backgroundColor = const Color.fromRGBO(238, 238, 238, 1);
        borderColor = isSelected
            ? const Color.fromRGBO(64, 158, 255, 1)
            : Colors.transparent;
        textColor = const Color.fromRGBO(100, 116, 139, 1);
        statusTextColor = const Color.fromRGBO(73, 149, 234, 1);
        break;
      case '空闲':
      default:
        backgroundColor = const Color.fromRGBO(238, 238, 238, 1);
        borderColor = isSelected
            ? const Color.fromRGBO(64, 158, 255, 1)
            : Colors.transparent;
        textColor = const Color.fromRGBO(100, 116, 139, 1);
        statusTextColor = const Color.fromRGBO(73, 149, 234, 1);
    }

    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedRoom = room['number'] as String;
          _selectedRoomId = room['roomId'] as int?;
        });
      },
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.r),
          color: backgroundColor,
          border: Border.all(
            color: borderColor,
            width: isSelected ? 3.w : 0,
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              room['number'] as String,
              style: TextStyle(
                fontSize: 28.sp,
                fontWeight: FontWeight.bold,
                color: textColor,
              ),
            ),
            SizedBox(height: 6.h),
            Builder(
              builder: (context) {
                if (status == '入住') {
                  return Text(
                    '入住',
                    style: TextStyle(
                      fontSize: 24.sp,
                      color: statusTextColor,
                    ),
                  );
                } else if (status == '待清洁') {
                  return Image.asset(
                    'lib/assets/icon/jth.png',
                    width: 24.sp,
                    height: 30.sp,
                  );
                } else {
                  return Text(
                    ' ',
                    style: TextStyle(
                      fontSize: 24.sp,
                      color: statusTextColor,
                    ),
                  );
                }
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBottomButtons(ServiceIndexCubit cubit) {
    final isRoomSelected = _selectedRoom != null;
    final isProcessing = cubit.state.isPoweringOn || cubit.state.isPoweringOff;
    return Row(
      children: [
        Expanded(
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color.fromRGBO(73, 149, 234, 1),
              disabledBackgroundColor: const Color.fromRGBO(204, 204, 204, 1),
              minimumSize: Size(double.infinity, 88.h),
              padding: EdgeInsets.zero,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16.r),
              ),
              elevation: 0,
            ),
            onPressed: isRoomSelected && !isProcessing
                ? () async {
                    try {
                      await cubit.powerOnRoom(_selectedRoom!);
                      if (context.mounted) {
                        showToast('送电成功');
                      }
                    } catch (e) {
                      if (context.mounted) {
                        showToast('送电失败: $e');
                      }
                    }
                  }
                : null,
            child: Text(
              '送电',
              style: TextStyle(
                  fontSize: 28.sp,
                  color: Colors.white,
                  fontWeight: FontWeight.w500),
            ),
          ),
        ),
        SizedBox(width: 16.w),
        Expanded(
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color.fromRGBO(229, 241, 255, 1),
              disabledBackgroundColor: const Color.fromRGBO(204, 204, 204, 1),
              minimumSize: Size(double.infinity, 88.h),
              padding: EdgeInsets.zero,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16.r),
                side: const BorderSide(
                  color: Color.fromRGBO(73, 149, 234, 1),
                  width: 1,
                ),
              ),
              elevation: 0,
            ),
            onPressed: isRoomSelected && !isProcessing
                ? () async {
                    try {
                      await cubit.powerOffRoom(_selectedRoom!);
                      if (context.mounted) {
                        showToast('断电成功');
                      }
                    } catch (e) {
                      if (context.mounted) {
                        showToast('断电失败: $e');
                      }
                    }
                  }
                : null,
            child: Text(
              '断电',
              style: TextStyle(
                  fontSize: 28.sp,
                  color: const Color.fromRGBO(100, 116, 139, 1),
                  fontWeight: FontWeight.w500),
            ),
          ),
        ),
        SizedBox(width: 16.w),
        Expanded(
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color.fromRGBO(100, 116, 139, 0.2),
              disabledBackgroundColor: const Color.fromRGBO(204, 204, 204, 1),
              minimumSize: Size(double.infinity, 88.h),
              padding: EdgeInsets.zero,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16.r),
              ),
              elevation: 0,
            ),
            onPressed: (isRoomSelected && _selectedRoomId != null)
                ? () {
                    context.pushRoute(ServiceRoomDetailRoute(
                      roomId: _selectedRoomId!,
                      roomNumber: _selectedRoom,
                    ));
                  }
                : null,
            child: Text(
              '查看',
              style: TextStyle(
                  fontSize: 28.sp,
                  color: const Color.fromRGBO(100, 116, 139, 1),
                  fontWeight: FontWeight.w500),
            ),
          ),
        ),
      ],
    );
  }
}
