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/home/abnormal/cubit/abnormal_cubit.dart';
import 'package:smart_hotel_app/views/home/abnormal/cubit/abnormal_state.dart';
import 'package:smart_hotel_app/views/home/abnormal/widget/alarm_info_block.dart';
import 'package:smart_hotel_app/views/home/abnormal/widget/temperature_block.dart';
import 'package:smart_hotel_app/views/home/abnormal/widget/temperature_char_block.dart';
import 'package:smart_hotel_app/utils/toast_utils.dart';

@RoutePage()
class AbnormalDetailView extends StatelessWidget {
  final int alertId;

  const AbnormalDetailView({super.key, required this.alertId});

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => AbnormalCubit(alertId: alertId),
      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<AbnormalCubit, AbnormalState>(
          builder: (context, state) {
            if (state.isLoading) {
              return const Center(child: CircularProgressIndicator());
            }
            if (state.error != null) {
              return Center(
                child: Text(
                  '加载失败: ${state.error}',
                  style: TextStyle(
                    fontSize: 28.sp,
                    color: const Color.fromRGBO(255, 100, 101, 1),
                  ),
                ),
              );
            }
            final alarmInfo = state.alarmInfo;
            if (alarmInfo == null) {
              return const SizedBox.shrink();
            }
            final cubit = context.read<AbnormalCubit>();
            return SingleChildScrollView(
              padding: EdgeInsets.symmetric(horizontal: 28.w),
              child: Column(
                children: [
                  TemperatureBlock(alarmInfo: alarmInfo),
                  SizedBox(height: 10.h),
                  TemperatureCharBlock(alarmInfo: alarmInfo),
                  SizedBox(height: 10.h),
                  AlarmInfoBlock(alarmInfo: alarmInfo),
                  SizedBox(height: 10.h),
                  _buildBottomButtons(context, cubit),
                  SizedBox(height: 30.h),
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildBottomButtons(BuildContext context, AbnormalCubit cubit) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 15.h),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          BlocBuilder<AbnormalCubit, AbnormalState>(
            builder: (context, state) {
              final isDisabled = state.isHandling || state.isHandled;
              return Container(
                width: double.infinity,
                height: 88.h,
                decoration: BoxDecoration(
                  color: isDisabled
                      ? const Color.fromRGBO(73, 149, 234, 0.4)
                      : const Color.fromRGBO(73, 149, 234, 1),
                  borderRadius: BorderRadius.circular(16.r),
                ),
                child: TextButton(
                  onPressed: isDisabled
                      ? null
                      : () => _handleConfirm(context, cubit),
                  child: state.isHandling
                      ? SizedBox(
                          width: 32.sp,
                          height: 32.sp,
                          child: CircularProgressIndicator(
                            strokeWidth: 3,
                            color: const Color.fromRGBO(237, 245, 255, 1),
                          ),
                        )
                      : Text(
                          state.isHandled ? '已处理' : '确认处理',
                          style: TextStyle(
                            fontSize: 28.sp,
                            color: const Color.fromRGBO(237, 245, 255, 1),
                          ),
                        ),
                ),
              );
            },
          ),
          SizedBox(height: 20.h),
          Container(
            width: double.infinity,
            height: 88.h,
            decoration: BoxDecoration(
              color: const Color.fromRGBO(100, 116, 139, 0.2),
              borderRadius: BorderRadius.circular(16.r),
            ),
            child: TextButton(
              onPressed: () {
                final deviceIdStr = cubit.state.alarmInfo?.alertDeviceId ?? '';
                final deviceId = int.tryParse(deviceIdStr) ?? 0;
                context.pushRoute(DeviceDetailRoute(deviceId: deviceId));
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '设备控制',
                    style: TextStyle(
                      fontSize: 28.sp,
                      color: const Color.fromRGBO(100, 116, 139, 1),
                    ),
                  ),
                  SizedBox(width: 8.w),
                  Image.asset(
                    "lib/assets/icon/right.png",
                    width: 24.w,
                    height: 21.h,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _handleConfirm(BuildContext context, AbnormalCubit cubit) async {
    try {
      await cubit.handleConfirm();
      if (context.mounted) {
        showToast('操作成功');
      }
    } catch (e) {
      if (context.mounted) {
        showToast('操作失败: $e');
      }
    }
  }
}