import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:smart_hotel_app/routes/app_router.gr.dart';
import 'package:smart_hotel_app/views/service/room/cubit/service_room_cubit.dart';
import 'package:smart_hotel_app/views/service/room/cubit/service_room_state.dart';
import 'package:smart_hotel_app/views/service/room/widget/room_overview_card.dart';
import 'package:smart_hotel_app/views/service/room/widget/room_device_status_card.dart';
import 'package:smart_hotel_app/views/service/room/widget/device_control_card.dart';
import 'package:smart_hotel_app/views/service/room/widget/room_bottom_buttons.dart';
import 'package:smart_hotel_app/utils/toast_utils.dart';

@RoutePage()
class ServiceRoomDetailView extends StatelessWidget {
  final int roomId;
  final String? roomNumber;

  const ServiceRoomDetailView({
    super.key,
    required this.roomId,
    this.roomNumber,
  });

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => ServiceRoomCubit(
        roomId: roomId,
        roomNumber: roomNumber ?? '',
      ),
      child: Scaffold(
        backgroundColor: const Color.fromRGBO(242, 243, 245, 1),
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios,
                color: Color.fromRGBO(100, 116, 139, 1)),
            onPressed: () {
              context.popRoute();
            },
          ),
          title: Text(
            '客房详情',
            style: TextStyle(
              color: const Color.fromRGBO(10, 13, 20, 1),
              fontSize: 32.sp,
              fontWeight: FontWeight.w200,
            ),
          ),
          centerTitle: true,
        ),
        body: BlocBuilder<ServiceRoomCubit, ServiceRoomState>(
          builder: (context, state) {
            if (state.isLoading) {
              return const Center(
                child: CircularProgressIndicator(),
              );
            }

            if (state.error != null) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      '加载失败',
                      style: TextStyle(
                        fontSize: 28.sp,
                        color: const Color.fromRGBO(100, 116, 139, 1),
                      ),
                    ),
                    SizedBox(height: 16.h),
                    ElevatedButton(
                      onPressed: () {
                        context.read<ServiceRoomCubit>().loadDetail();
                      },
                      child: const Text('重试'),
                    ),
                  ],
                ),
              );
            }

            final cubit = context.read<ServiceRoomCubit>();
            return SingleChildScrollView(
              padding: EdgeInsets.symmetric(horizontal: 28.w),
              child: Column(
                children: [
                  SizedBox(height: 20.h),
                  RoomOverviewCard(
                    roomNumber: state.roomNumber,
                    roomStatus: state.roomStatus,
                    statusTags: state.statusTags,
                  ),
                  SizedBox(height: 20.h),
                  RoomDeviceStatusCard(
                    devices: state.roomDevices,
                  ),
                  SizedBox(height: 20.h),
                  DeviceControlCard(
                    mainPowerOn: state.mainPowerOn,
                    controlDevices: state.controlDevices,
                    onMainPowerToggle: (value) async {
                      try {
                        await cubit.toggleMainPowerForSwitch(value);
                        if (context.mounted) {
                          showToast(value ? '送电成功' : '断电成功');
                        }
                      } catch (e) {
                        if (context.mounted) {
                          showToast('操作失败: $e');
                        }
                      }
                    },
                    onDeviceToggle: (index, value) =>
                        cubit.toggleControlDevice(index, value),
                    onDeviceTap: (index, device) {
                      if (device.name == '空调' || device.name?.contains('空调') == true) {
                        context.pushRoute(ServiceDeviceDetailRoute(deviceId: device.deviceId));
                      }
                    },
                  ),
                  SizedBox(height: 20.h),
                  RoomBottomButtons(
                    isProcessing: state.isTogglingPower,
                    onPowerOn: () async {
                      try {
                        await cubit.toggleMainPower(true);
                        if (context.mounted) {
                          showToast('送电成功');
                        }
                      } catch (e) {
                        if (context.mounted) {
                          showToast('送电失败: $e');
                        }
                      }
                    },
                    onPowerOff: () async {
                      try {
                        await cubit.toggleMainPower(false);
                        if (context.mounted) {
                          showToast('断电成功');
                        }
                      } catch (e) {
                        if (context.mounted) {
                          showToast('断电失败: $e');
                        }
                      }
                    },
                  ),
                  SizedBox(height: 20.h),
                ],
              ),
            );
          },
        ),
      ),
    );
  }
}
