// ignore_for_file: must_be_immutable

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/scene/bloc/create_scene/create_scene_bloc.dart';
import 'package:syncrow_app/features/scene/model/scene_static_function.dart';

class AlertDialogCountdown extends StatefulWidget {
  AlertDialogCountdown({
    super.key,
    required this.durationValue,
    this.functionValue,
    required this.function,
  });

  final int durationValue;
  dynamic functionValue;
  SceneStaticFunction function;

  @override
  State<AlertDialogCountdown> createState() => _AlertDialogCountdownState();
}

class _AlertDialogCountdownState extends State<AlertDialogCountdown> {
  @override
  didChangeDependencies() {
    super.didChangeDependencies();

    final tempTaskList = context.read<CreateSceneBloc>().tempTasksList;

    for (var element in tempTaskList) {
      if (element.code == widget.function.code) {
        durationInSeconds = element.functionValue;
      } else {
        context
            .read<CreateSceneBloc>()
            .add(RemoveFromSelectedValueById(code: widget.function.code));
      }
    }
    if (widget.functionValue != null) {
      setState(() {
        durationInSeconds = widget.functionValue;
      });
    }
  }

  int durationInSeconds = 0;
  // Convert seconds to Duration.
  Duration get duration => Duration(seconds: widget.durationValue);
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 120,
      color: Colors.white,
      child: CupertinoTimerPicker(
        itemExtent: 120,
        mode: CupertinoTimerPickerMode.hm,
        initialTimerDuration: duration,
        onTimerDurationChanged: (newDuration) {
          setState(() {
            durationInSeconds = newDuration.inSeconds;
          });
          context.read<CreateSceneBloc>().add(SelectedValueEvent(
              value: newDuration.inSeconds,
              code: widget.function.deviceId == 'delay'
                  ? 'delay'
                  : widget.function.code));
        },
      ),
    );
  }
}
