import 'dart:async';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'rest_timer_service.g.dart';

class RestTimerState {
  final bool isActive;
  final int remainingSeconds;
  final int totalSeconds;

  const RestTimerState({
    required this.isActive,
    required this.remainingSeconds,
    required this.totalSeconds,
  });

  double get progress =>
      totalSeconds > 0 ? remainingSeconds / totalSeconds : 0.0;

  RestTimerState copyWith({
    bool? isActive,
    int? remainingSeconds,
    int? totalSeconds,
  }) {
    return RestTimerState(
      isActive: isActive ?? this.isActive,
      remainingSeconds: remainingSeconds ?? this.remainingSeconds,
      totalSeconds: totalSeconds ?? this.totalSeconds,
    );
  }
}

@riverpod
class RestTimer extends _$RestTimer {
  Timer? _timer;

  @override
  RestTimerState build() {
    ref.onDispose(() {
      _timer?.cancel();
    });

    return const RestTimerState(
      isActive: false,
      remainingSeconds: 0,
      totalSeconds: 0,
    );
  }

  void start(int seconds) {
    cancel();

    state = RestTimerState(
      isActive: true,
      remainingSeconds: seconds,
      totalSeconds: seconds,
    );

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (state.remainingSeconds > 0) {
        state = state.copyWith(
          remainingSeconds: state.remainingSeconds - 1,
        );
      } else {
        complete();
      }
    });
  }

  void skip() {
    cancel();
    state = state.copyWith(
      isActive: false,
      remainingSeconds: 0,
    );
  }

  void complete() {
    cancel();
    state = state.copyWith(
      isActive: false,
      remainingSeconds: 0,
    );
  }

  void cancel() {
    _timer?.cancel();
    _timer = null;
  }
}
