import 'dart:async';

import 'package:appinio_swiper/appinio_swiper.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/config/routes.dart';
import 'package:mohem_flutter_app/ui/marathon/widgets/question_card.dart';

class MarathonProvider extends ChangeNotifier {
  final AppinioSwiperController swiperController = AppinioSwiperController();

  bool _itsMarathonTime = false;

  bool get itsMarathonTime => _itsMarathonTime;

  set itsMarathonTime(bool value) {
    _itsMarathonTime = value;
    notifyListeners();
  }

  bool _isMarathonCompleted = false;

  bool get isMarathonCompleted => _isMarathonCompleted;

  set isMarathonCompleted(bool value) {
    _isMarathonCompleted = value;
    notifyListeners();
  }

  void swipeCardLeft() {
    currentQuestionNumber = currentQuestionNumber + 1;
    swiperController.swipeLeft();
    notifyListeners();
  }

  int _currentQuestionNumber = 1;
  final int totalQuestions = 10;

  int get currentQuestionNumber => _currentQuestionNumber;

  set currentQuestionNumber(int value) {
    _currentQuestionNumber = value;
    notifyListeners();
  }

  void resetAll() {
    isSelectedOptions[0] = false;
    isSelectedOptions[1] = false;
    isSelectedOptions[2] = false;
    isSelectedOptions[3] = false;
  }

  Timer timerU = Timer.periodic(const Duration(seconds: 1), (Timer timer) {});
  int start = 8;

  void startTimer(BuildContext context) {
    start = 8;
    const Duration oneSec = Duration(seconds: 1);
    timerU = Timer.periodic(
      oneSec,
      (Timer timer) async {
        if (start == 0) {
          if (currentQuestionNumber == 9) {
            timer.cancel();
            cancelTimer();
            isMarathonCompleted = true;
            await Future<dynamic>.delayed(const Duration(seconds: 3)).whenComplete(
              () => Navigator.pushReplacementNamed(
                context,
                AppRoutes.marathonWinnerSelection,
              ),
            );

            resetValues();

            return;
          }
          resetAll();
          timer.cancel();
          cancelTimer();
          swipeCardLeft();
        } else {
          start--;
        }
        notifyListeners();
      },
    );
  }

  void resetValues() {
    timerU.cancel();
    _isMarathonCompleted = false;
    _currentQuestionNumber = 1;
    notifyListeners();
  }

  void cancelTimer() {
    timerU.cancel();
    notifyListeners();
  }
}
