import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:syncrow_app/features/devices/bloc/6_scene_switch_bloc/6_scene_state.dart';
import 'package:syncrow_app/features/devices/bloc/acs_bloc/acs_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/acs_bloc/acs_event.dart';
import 'package:syncrow_app/features/devices/bloc/acs_bloc/acs_state.dart';
import 'package:syncrow_app/features/devices/model/ac_model.dart';
import 'package:syncrow_app/features/devices/model/device_model.dart';
import 'package:syncrow_app/features/devices/view/widgets/ACs/custom_halfhour_timer_picker.dart';
import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_large.dart';
import 'package:syncrow_app/generated/assets.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';
import 'package:syncrow_app/utils/resource_manager/font_manager.dart';

class AcTimerPage extends StatelessWidget {
  final DeviceModel device;
  final String deviceCode;
  final String switchCode;
  final AcStatusModel deviceStatus;

  const AcTimerPage(
      {required this.device,
      required this.deviceCode,
      required this.switchCode,
      required this.deviceStatus,
      super.key});

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion(
      value: SystemUiOverlayStyle(
        statusBarColor: ColorsManager.primaryColor.withOpacity(0.5),
        statusBarIconBrightness: Brightness.light,
      ),
      child: BlocProvider(
        create: (context) => ACsBloc(acId: device.uuid ?? ''),
        child: BlocBuilder<ACsBloc, AcsState>(
          builder: (context, state) {
            final acBloc = BlocProvider.of<ACsBloc>(context);
            Duration duration = Duration.zero;
            int selectedValue = 0;
            int countNum = 0;
            if (state is AcsInitialState) {
              acBloc.add(GetCounterEvent(deviceCode: deviceCode));
            } else if (state is UpdateTimerState) {
              countNum = state.seconds;
            } else if (state is TimerRunInProgress) {
              countNum = state.remainingTime;
            } else if (state is TimerRunComplete) {
              countNum = 0;
            }
            return PopScope(
                canPop: false,
                onPopInvoked: (didPop) {
                  if (!didPop) {
                    acBloc.add(OnClose());
                    Navigator.pop(context);
                  }
                },
                child: DefaultTabController(
                    length: 2,
                    child: DefaultScaffold(
                      appBar: AppBar(
                        backgroundColor: Colors.transparent,
                        centerTitle: true,
                        title: const BodyLarge(
                          text: 'Countdown',
                          fontColor: ColorsManager.primaryColor,
                          fontWeight: FontsManager.bold,
                        ),
                      ),
                      child: state is AcsLoadingState
                          ? const Center(child: CircularProgressIndicator())
                          : Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Container(
                                  width: MediaQuery.of(context).size.width,
                                  decoration: const ShapeDecoration(
                                    color: ColorsManager.onPrimaryColor,
                                    shape: RoundedRectangleBorder(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(30)),
                                    ),
                                  ),
                                ),
                                Center(
                                  child: SizedBox(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        countNum > 0
                                            ? BodyLarge(
                                                text: formatDuration(countNum),
                                                fontColor: ColorsManager
                                                    .slidingBlueColor,
                                                fontSize: 40,
                                              )
                                            : SizedBox(
                                                child: CustomHalfHourPicker(
                                                  onValueChanged: (value) {
                                                    selectedValue =
                                                        (value * 10).toInt();
                                                    if (selectedValue == 5) {
                                                      duration = const Duration(
                                                          minutes: 30);
                                                      countNum =
                                                          duration.inSeconds;
                                                    } else {
                                                      duration = Duration(
                                                          minutes:
                                                              selectedValue *
                                                                  6);
                                                      countNum =
                                                          duration.inSeconds;
                                                    }
                                                  },
                                                ),
                                              ),
                                        GestureDetector(
                                            onTap: () {
                                              if (state is LoadingNewSate) {
                                                return;
                                              }
                                              if (countNum > 0) {
                                                acBloc.add(SetCounterValue(
                                                    seconds: countNum,
                                                    deviceCode:
                                                        'countdown_time',
                                                    duration: selectedValue));
                                              } else if (duration !=
                                                  Duration.zero) {
                                                acBloc.add(SetCounterValue(
                                                    seconds: 0,
                                                    deviceCode:
                                                        'countdown_time',
                                                    duration: selectedValue));
                                              }
                                            },
                                            child: SvgPicture.asset(countNum > 0
                                                ? Assets.pauseIcon
                                                : Assets.playIcon)),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                    )));
          },
        ),
      ),
    );
  }

  String formatDuration(int seconds) {
    final hours = (seconds ~/ 3600).toString().padLeft(2, '0');
    final minutes = ((seconds % 3600) ~/ 60).toString().padLeft(2, '0');
    final secs = (seconds % 60).toString().padLeft(2, '0');
    return '$hours:$minutes:$secs';
  }
}
