import 'dart:async';
import 'package:flutter/material.dart';

class RemainingTime {
  ValueNotifier<int> remainingSeconds = ValueNotifier<int>(0);
  ValueNotifier<bool> canResend = ValueNotifier<bool>(false);
  DateTime? _expiryTime;
  Timer? _timer;

  void initializeFromExpiry({required String expiryTimeString}) {
    try {
      _expiryTime = DateTime.fromMillisecondsSinceEpoch(int.parse(expiryTimeString)).toUtc();
      _updateRemainingSeconds();
      startTimer();
    } catch (e) {
      debugPrint("Error initializing timer: $e");
      remainingSeconds.value = 0;
      canResend.value = true;
    }
  }

  void _updateRemainingSeconds() {
    final now = DateTime.now().toUtc();
    if (_expiryTime == null) return;
    final difference = _expiryTime!.difference(now).inSeconds;
    remainingSeconds.value = difference > 0 ? difference : 0;
    canResend.value = remainingSeconds.value <= 0;
  }

  void startTimer() {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      _updateRemainingSeconds();
      if (remainingSeconds.value <= 0) {
        timer.cancel();
      }
    });
  }

  String formatTime() {
    final seconds = remainingSeconds.value;
    if (seconds >= 3600) {
      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";
    } else {
      final minutes = (seconds ~/ 60).toString().padLeft(2, '0');
      final secs = (seconds % 60).toString().padLeft(2, '0');
      return "$minutes:$secs";
    }
  }

  void dispose() {
    _timer?.cancel();
    remainingSeconds.dispose();
    canResend.dispose();
  }
}