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.w500,
            ),
          ),
          centerTitle: true,
        ),
        body: BlocBuilder<ServiceRoomCubit, ServiceRoomState>(
          builder: (context, state) {
            if (state.isLoading) {
              return const Center(
                child: CircularProgressIndicator(color: const Color.fromRGBO(66, 165, 245, 1.0)),
              );
            }

            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(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: 20.h),
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(24.r),
                    ),
                    child: Column(
                      children: [
                        RoomOverviewCard(
                          roomNumber: state.roomNumber,
                          roomStatus: state.roomStatus,
                          statusTags: state.statusTags,
                        ),
                        Divider(
                          height: 0.5.h,
                          color: const Color.fromRGBO(100, 116, 139, 0.2),
                          thickness: 0.5,
                          indent: 28.w,
                          endIndent: 28.w,
                        ),
                        RoomDeviceStatusCard(
                          devices: state.roomDevices,
                        ),
                      ],
                    ),
                  ),
                  SizedBox(height: 20.h),
                  Text(
                    '设备控制',
                    style: TextStyle(
                      fontSize: 32.sp,
                      fontWeight: FontWeight.bold,
                      color: const Color.fromRGBO(10, 13, 20, 1.0),
                    ),
                  ),
                  SizedBox(height: 10.h),
                  DeviceControlCard(
                    mainPowerOn: state.mainPowerOn,
                    controlDevices: state.controlDevices,
                    onMainPowerToggle: (value) async {
                      try {
                        await cubit.toggleMainPower(value);
                        if (context.mounted) {
                          showToast(value ? '送电成功' : '断电成功');
                        }
                      } catch (e) {
                        if (context.mounted) {
                          showToast('操作失败: $e');
                        }
                      }
                    },
                    onDeviceToggle: (index, value) =>
                        cubit.toggleControlDevice(index, value),
                    onDeviceTap: (index, device) {
                      /// item click
                      if (device.name.contains('空调')) {
                        context.pushRoute(ServiceDeviceDetailRoute(deviceId: device.deviceId));
                      }
                    },
                  ),
                  SizedBox(height: 20.h),
                  RoomBottomButtons(
                    isPoweringOn: state.isPoweringOn,
                    isPoweringOff: state.isPoweringOff,
                    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),
                ],
              ),
            );
          },
        ),
      ),
    );
  }
}
