import 'dart:async';
import 'package:cargocalculaterapp/core/theme/app_text_styles.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/auth_confirm/auth_confirm_bloc.dart';

class TimerWidget extends StatefulWidget {
  const TimerWidget({super.key});

  @override
  State<TimerWidget> createState() => _TimerWidgetState();
}

class _TimerWidgetState extends State<TimerWidget> {
  Timer? timer;
  int time = 60;
  String timeText = "60";

  @override
  void initState() {
    if (timer?.isActive ?? false) {
      timer?.cancel();
    }
    timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) async {
      time--;
      if (time == 0) {
        timer.cancel();
        context.read<AuthConfirmBloc>().add(
          const TimerChangedEvent(isVisible: false),
        );
      }
      setState(() {
        timeText = time.toString().padLeft(2, "0");
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Text(" 00:$timeText", style: AppTextStyles.timerStyle);
  }

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }
}
