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/garage_door_bloc/garage_door_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/garage_door_bloc/garage_door_event.dart';
import 'package:syncrow_app/features/devices/bloc/garage_door_bloc/garage_door_state.dart';
import 'package:syncrow_app/features/devices/model/device_model.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 TimerPage extends StatelessWidget {
  final DeviceModel device;
  final String deviceCode;
  final String switchCode;
  const TimerPage(
      {required this.device,
      required this.deviceCode,
      required this.switchCode,
      super.key});

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion(
      value: SystemUiOverlayStyle(
        statusBarColor: ColorsManager.primaryColor.withOpacity(0.5),
        statusBarIconBrightness: Brightness.light,
      ),
      child: BlocProvider(
        create: (context) => GarageDoorBloc(GDId: device.uuid ?? '')
          ..add(GetCounterEvent(deviceCode: deviceCode)),
        child: BlocBuilder<GarageDoorBloc, GarageDoorSensorState>(
          builder: (context, state) {
            final oneGangBloc = BlocProvider.of<GarageDoorBloc>(context);
            Duration duration = Duration.zero;
            int countNum = 0;
            if (state is UpdateTimerState) {
              countNum = state.seconds;
            } else if (state is TimerRunInProgress) {
              countNum = state.remainingTime;
            } else if (state is TimerRunComplete) {
              countNum = 0;
            } else if (state is LoadingNewSate) {
              countNum = 0;
            }
            return PopScope(
                canPop: false,
                onPopInvoked: (didPop) {
                  if (!didPop) {
                    oneGangBloc.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 GarageDoorLoadingState
                          ? 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: Container(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        countNum > 0
                                            ? BodyLarge(
                                                text: _formatDuration(countNum),
                                                fontColor: ColorsManager
                                                    .slidingBlueColor,
                                                fontSize: 40,
                                              )
                                            : CupertinoTimerPicker(
                                                mode:
                                                    CupertinoTimerPickerMode.hm,
                                                onTimerDurationChanged:
                                                    (Duration newDuration) {
                                                  duration = newDuration;
                                                },
                                              ),
                                        GestureDetector(
                                            onTap: () {
                                              if (state is LoadingNewSate) {
                                                return;
                                              }
                                              if (countNum > 0) {
                                                oneGangBloc.add(
                                                    const SetCounterValue(
                                                        deviceCode:
                                                            'countdown_1',
                                                        duration:
                                                            Duration.zero));
                                              } else if (duration !=
                                                  Duration.zero) {
                                                oneGangBloc.add(SetCounterValue(
                                                    deviceCode: 'countdown_1',
                                                    duration: duration));
                                              }
                                            },
                                            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';
  }
}
