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';

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

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

class _RoomManagementBlockState extends State<RoomManagementBlock> {
  String? _selectedFloor;
  String? _selectedType;
  String? _selectedRoom;
  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 floor in cubit.state.floors) {
        allRooms.addAll(cubit.getRoomsByFloor(floor));
      }
    } 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;
  }

  @override
  Widget build(BuildContext context) {
    final cubit = context.read<ServiceIndexCubit>();
    return 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),
          _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),
                ),
              ),
            ),
          _buildBottomButtons(cubit),
        ],
      ),
    );
  }

  Widget _buildFloorSelector(ServiceIndexCubit cubit) {
    final floors = cubit.state.floors;
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: floors.map((floor) {
          final isSelected = _selectedFloor == floor;
          final displayFloor = floor.replaceAll('楼', '');
          return Padding(
            padding: EdgeInsets.only(right: 24.w),
            child: GestureDetector(
              onTap: () {
                setState(() {
                  if (_selectedFloor == floor) {
                    _selectedFloor = null;
                  } else {
                    _selectedFloor = floor;
                  }
                  _searchController.clear();
                  _searchText = '';
                });
              },
              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 types = ['客房', '大堂', '过道', '会议', '餐厅'];
    return Row(
      children: types.asMap().entries.map((entry) {
        final index = entry.key;
        final type = entry.value;
        final isSelected = _selectedType == type;
        return Expanded(
          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;
                  }
                });
              },
              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;
        });
      },
      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;
    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
                ? () {
                    cubit.powerOnRoom(_selectedRoom!);
                  }
                : 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
                ? () {
                    cubit.powerOffRoom(_selectedRoom!);
                  }
                : 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
                ? () {
                    context.pushRoute(ServiceRoomDetailRoute(roomNumber: _selectedRoom));
                  }
                : null,
            child: Text(
              '查看',
              style: TextStyle(
                  fontSize: 28.sp,
                  color: const Color.fromRGBO(100, 116, 139, 1),
                  fontWeight: FontWeight.w500),
            ),
          ),
        ),
      ],
    );
  }
}
