// Dart imports:
import 'dart:async';

// Flutter imports:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

// Package imports:
import 'package:provider/provider.dart';
import 'package:remever/common/resources.dart';
import 'package:remever/common/widgets/typography.dart';
import 'package:remever/common/widgets/w_if.dart';
import 'package:remever/common/widgets/wspace.dart';
import 'package:remever/components/extensions/context.dart';
import 'package:remever/components/extensions/state.dart';

class ResendTimer extends StatefulWidget {
  const ResendTimer({required this.onTap, super.key});

  final Function() onTap;

  @override
  State<ResendTimer> createState() => _ResendTimerState();
}

class _ResendTimerState extends State<ResendTimer> {
  Timer? _timer;
  int _start = 60;

  void _startTimer() {
    const Duration oneSec = Duration(seconds: 1);
    _timer = Timer.periodic(oneSec, (Timer timer) {
      if (_start > 0) {
        safeSetState(() {
          _start--;
        });
      } else {
        _timer?.cancel();
      }
    });
  }

  @override
  void initState() {
    _startTimer();
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Wif(
      condition: _start == 0,
      builder: (BuildContext context) => _buildResend(),
      fallback: (BuildContext context) => _buildTimer(),
    );
  }

  Widget _buildResend() {
    return InkWell(
      onTap: () async {
        await widget.onTap();
        safeSetState(() => _start = 60);
        _startTimer();
      },
      child: AppTypography(
        'Получить новый код на e-mail',
        type: Regular14px(),
        color: AppColors.primary,
      ),
    );
  }

  Widget _buildTimer() {
    return Row(
      children: <Widget>[
        AppTypography(
          'Получить новый код можно будет через: ',
          type: Regular14px(),
          color: AppColors.disabled,
        ),
        AppTypography(
          '$_start сек',
          type: Regular14px(),
          color: AppColors.disabled,
        ),
      ],
    );
  }
}
