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/utils/toast_utils.dart';

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

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ServiceIndexCubit, ServiceIndexState>(
      builder: (context, state) {
        final cubit = context.read<ServiceIndexCubit>();
        return Container(
          width: double.infinity,
          padding: EdgeInsets.all(28.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(state, cubit),
              SizedBox(height: 24.h),
              _buildTypeSelector(state, cubit),
              SizedBox(height: 24.h),
              _buildSearchBox(state, cubit),
              SizedBox(height: 32.h),
              _buildLine(),
              SizedBox(height: 32.h),
              _buildRoomGrid(state, cubit),
              SizedBox(height: 24.h),
              if (state.selectedRoom != null) ...[
                _buildLine(),
                SizedBox(height: 24.h),
                _buildRoomDetail(state, cubit),
                SizedBox(height: 10.h),
              ],
              _buildBottomButtons(state, cubit, context),
            ],
          ),
        );
      },
    );
  }

  Widget _buildFloorSelector(ServiceIndexState state, ServiceIndexCubit cubit) {
    final floors = state.floors;
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        spacing: 30.w,
        children: (floors ?? []).map((floorMap) {
          final floorName = floorMap.values.first;
          final floorId = floorMap.keys.first;
          final isSelected = state.selectedFloor == floorName;
          return GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () => cubit.toggleFloor(floorName, floorId),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              spacing: 4.h,
              children: [
                Text(
                  floorName,
                  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,
                  ),
                ),
                Container(
                  width: 60.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(ServiceIndexState state, ServiceIndexCubit cubit) {
    return Row(
      spacing: 10.w,
      children: state.areas.asMap().entries.map((entry) {
        final type = entry.value;
        final isSelected = state.selectedType == type;
        return GestureDetector(
          onTap: () => cubit.toggleType(type),
          child: Container(
            alignment: Alignment.center,
            width: 110.w,
            height: 45.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: 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(ServiceIndexState state, ServiceIndexCubit cubit) {
    return Container(
      height: 80.h,
      padding: EdgeInsets.symmetric(horizontal: 20.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(
        spacing: 20.w,
        children: [
          Icon(
            Icons.search,
            color: const Color.fromRGBO(100, 116, 139, 1),
            size: 46.sp,
          ),
          Expanded(
            child: _SearchBox(
              selectedFloor: state.selectedFloor,
              onChanged: (value) => cubit.setSearchText(value),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLine() {
    return Divider(
      height: 0.5.h,
      color: const Color.fromRGBO(100, 116, 139, 0.2),
      thickness: 0.5,
    );
  }

  Widget _buildRoomGrid(ServiceIndexState state, ServiceIndexCubit cubit) {
    final filteredRooms = cubit.getFilteredRooms();

    final floorPart = state.selectedFloor ?? '';
    final areaLabel = state.selectedType ?? '全部';
    final filterLabel = floorPart.isNotEmpty
        ? '$areaLabel·$floorPart·左右滑动选择'
        : '$areaLabel·左右滑动选择';

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      spacing: 18.h,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              filterLabel,
              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),
              ),
            ),
          ],
        ),
        if (filteredRooms.isEmpty)
          Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(vertical: 40.h),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8.r),
              color: const Color.fromRGBO(245, 245, 245, 1),
            ),
            child: Center(
              child: Text(
                '未找到匹配的房间',
                style: TextStyle(
                  fontSize: 24.sp,
                  color: const Color.fromRGBO(153, 153, 153, 1),
                ),
              ),
            ),
          )
        else
          _RoomGrid(
            filteredRooms: filteredRooms,
            selectedFloor: state.selectedFloor,
            selectedType: state.selectedType,
            selectedRoom: state.selectedRoom,
            cubit: cubit,
          ),
      ],
    );
  }

  Widget _buildRoomDetail(ServiceIndexState state, ServiceIndexCubit cubit) {
    final room = cubit.getSelectedRoomDetail();
    if (room == null) return const SizedBox.shrink();

    final items = [
      ('房间有无人', room['occupancyStatus'] == '1' ? '有人' : '无人'),
      ('房间状态', room['occupancyStatus'] == '1' ? '入住' : '空闲'),
      // ('清洁灯', room['cleanStatus'] == '2' ? '已完成' : '待清洁'),
      // ('设备开关', room['devicePowerStatus'] == '1' ? '开' : '关'),
    ];

    return Column(
      children: items.map((item) {
        return Padding(
          padding: EdgeInsets.only(bottom: 16.h),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                item.$1,
                style: TextStyle(
                  fontSize: 24.sp,
                  color: const Color.fromRGBO(100, 116, 139, 1),
                ),
              ),
              Text(
                item.$2,
                style: TextStyle(
                  fontSize: 24.sp,
                  color: const Color.fromRGBO(73, 149, 234, 1),
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        );
      }).toList(),
    );
  }

  Widget _buildBottomButtons(ServiceIndexState state, ServiceIndexCubit cubit, BuildContext context) {
    final isRoomSelected = state.selectedRoom != null;
    return Row(
      spacing: 16.w,
      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, 70.h),
              padding: EdgeInsets.zero,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16.r),
              ),
              elevation: 0,
            ),
            onPressed: isRoomSelected && !state.isPoweringOn
                ? () async {
                    try {
                      await cubit.powerOnRoom(state.selectedRoom!);
                      if (context.mounted) {
                        showToast('送电成功');
                      }
                    } catch (e) {
                      if (context.mounted) {
                        showToast('送电失败: $e');
                      }
                    }
                  }
                : null,
            child: state.isPoweringOn
                ? SizedBox(
                    width: 32.w,
                    height: 32.w,
                    child: CircularProgressIndicator(
                      strokeWidth: 3.w,
                      color: const Color.fromRGBO(66, 165, 245, 1.0),
                    ),
                  )
                : Text(
                    '送电',
                    style: TextStyle(
                        fontSize: 28.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w500),
                  ),
          ),
        ),
        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, 70.h),
              padding: EdgeInsets.zero,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16.r),
              ),
              elevation: 0,
            ),
            onPressed: isRoomSelected && !state.isPoweringOff
                ? () async {
                    try {
                      await cubit.powerOffRoom(state.selectedRoom!);
                      if (context.mounted) {
                        showToast('断电成功');
                      }
                    } catch (e) {
                      if (context.mounted) {
                        showToast('断电失败: $e');
                      }
                    }
                  }
                : null,
            child: state.isPoweringOff
                ? SizedBox(
                    width: 32.w,
                    height: 32.w,
                    child: CircularProgressIndicator(
                      strokeWidth: 3.w,
                      color: const Color.fromRGBO(229, 241, 255, 1),
                    ),
                  )
                : Text(
                    '断电',
                    style: TextStyle(
                        fontSize: 28.sp,
                        color: const Color.fromRGBO(100, 116, 139, 1),
                        fontWeight: FontWeight.w500),
                  ),
          ),
        ),
        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, 70.h),
              padding: EdgeInsets.zero,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16.r),
              ),
              elevation: 0,
            ),
            onPressed: (isRoomSelected && state.selectedRoomId != null)
                ? () {
                    context.pushRoute(ServiceRoomDetailRoute(
                      roomId: state.selectedRoomId!,
                      roomNumber: state.selectedRoom,
                    ));
                  }
                : null,
            child: Text(
              '查看',
              style: TextStyle(
                  fontSize: 28.sp,
                  color: const Color.fromRGBO(100, 116, 139, 1),
                  fontWeight: FontWeight.w500),
            ),
          ),
        ),
      ],
    );
  }

}



/// 搜索框 — 独立 StatefulWidget 管理 TextEditingController
class _SearchBox extends StatefulWidget {
  final String? selectedFloor;
  final ValueChanged<String> onChanged;

  const _SearchBox({required this.selectedFloor, required this.onChanged});

  @override
  State<_SearchBox> createState() => _SearchBoxState();
}

class _SearchBoxState extends State<_SearchBox> {
  final TextEditingController _controller = TextEditingController();
  String? _lastFloor;

  @override
  void didUpdateWidget(covariant _SearchBox oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.selectedFloor != _lastFloor && widget.selectedFloor != null) {
      _controller.clear();
    }
    _lastFloor = widget.selectedFloor;
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: _controller,
      onChanged: widget.onChanged,
      style: TextStyle(
        fontSize: 28.sp,
        color: const Color.fromRGBO(100, 116, 139, 1),
      ),
      decoration: InputDecoration(
        hintText: '输入房号快速查找，如301...',
        hintStyle: TextStyle(
          fontSize: 26.sp,
          color: const Color.fromRGBO(100, 116, 139, 1),
        ),
        border: InputBorder.none,
        contentPadding: EdgeInsets.symmetric(vertical: 16.h),
        isCollapsed: true,
      ),
    );
  }
}



/// 房间网格 — 独立 StatefulWidget 管理 ScrollController，楼层/区域切换时自动滚回起始位置
class _RoomGrid extends StatefulWidget {
  final List<Map<String, dynamic>> filteredRooms;
  final String? selectedFloor;
  final String? selectedType;
  final String? selectedRoom;
  final ServiceIndexCubit cubit;

  const _RoomGrid({
    required this.filteredRooms,
    required this.selectedFloor,
    required this.selectedType,
    required this.selectedRoom,
    required this.cubit,
  });

  @override
  State<_RoomGrid> createState() => _RoomGridState();
}

class _RoomGridState extends State<_RoomGrid> {
  final ScrollController _scrollController = ScrollController();
  String? _prevFloor;
  String? _prevType;

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 楼层或区域切换后，房间网格滚回起始位置
    if (widget.selectedFloor != _prevFloor || widget.selectedType != _prevType) {
      _prevFloor = widget.selectedFloor;
      _prevType = widget.selectedType;
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (_scrollController.hasClients) {
          _scrollController.jumpTo(0);
        }
      });
    }

    const crossAxisCount = 12;
    return SingleChildScrollView(
      controller: _scrollController,
      scrollDirection: Axis.horizontal,
      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: widget.filteredRooms.length,
          itemBuilder: (context, index) {
            final room = widget.filteredRooms[index];
            final isSelected = widget.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;
    switch (status) {
      case '入住':
        backgroundColor = const Color.fromRGBO(229, 241, 255, 1);
        borderColor = isSelected
            ? const Color.fromRGBO(73, 149, 234, 1)
            : Colors.transparent;
        textColor = 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);
        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);
    }

    return GestureDetector(
      onTap: () => widget.cubit.selectRoom(
        room: room['number'] as String,
        roomId: room['roomId'] as int?,
      ),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(16.r),
          color: backgroundColor,
          border: Border.all(
            color: borderColor,
            width: isSelected ? 1.w : 0,
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          spacing: 6.h,
          children: [
            Text(
              room['number'] as String,
              style: TextStyle(
                fontSize: 28.sp,
                fontWeight: FontWeight.w500,
                color: textColor,
              ),
              textAlign: TextAlign.center,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            Builder(
              builder: (context) {
                if (status == '入住') {
                  return Text(
                    '入住',
                    style: TextStyle(
                      fontSize: 24.sp,
                      color: const Color.fromRGBO(73, 149, 234, 1),
                    ),
                  );
                } 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: const Color.fromRGBO(73, 149, 234, 1),
                    ),
                  );
                }
              },
            ),
          ],
        ),
      ),
    );
  }
}
