import 'dart:async';
import 'dart:math';

import 'package:auto_route/auto_route.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mnemo_cards/features/tests/progress_widget.dart';
import 'package:rxdart/rxdart.dart';

import '../../di/locator.dart';
import '../../theme/themes.dart';

class TestProgressWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _TestProgressWidgetState();

  const TestProgressWidget({super.key});
}

class _TestProgressWidgetState extends State<TestProgressWidget> {
  List<Result> results = [];
  int length = 0;

  Stream<Duration>? timer;

  bool _active = false;

  void _updateDataListener() {
    if (!_active) {
      _active = true;
      Timer(Duration(milliseconds: 100), () => _updateData());
    }
  }

  void _updateData() {
    results = <Result>[
      Result.correct,
    ];
    length = locator.testManager.questions.length + 1;
    final pageController = locator.testManager.pageController;
    for (final state in locator.testManager.states) {
      if (state.isAnswered) {
        if (state.isCorrect) {
          results.add(Result.correct);
        } else {
          // results.add(Result.wrong);
          results.add(Result.wrong);
        }
      } else if (state.isSkipped) {
        results.add(Result.skiped);
      } else {
        results.add(Result.not_visited);
      }
    }
    print('Update data ${results.map((e) => e.name).join(' ')}');
    if (mounted) {
      setState(() {});
    }
    _active = false;
  }

  @override
  void initState() {
    super.initState();
    locator.testManager.pageController.removeListener(_updateDataListener);
    locator.testManager.pageController.addListener(_updateDataListener);
    // timer = Stream.periodic(
    //   Duration(seconds: 1),
    //   (tick) => Duration(seconds: 300 - tick - 1),
    // ).startWith(Duration(seconds: 300)).take(300);
    _updateData();
  }

  @override
  Widget build(BuildContext context) {
    return ProgressWidget(
      results,
      length,
      locator.testManager.color,
      timer: timer,
    );
  }
}
