import 'dart:async';

import 'package:flutter/cupertino.dart';

class SendCodeButton extends StatefulWidget {
  final Future<bool> Function() sendCode;

  const SendCodeButton({
    super.key,
    required this.sendCode,
  });

  @override
  State<SendCodeButton> createState() => _SendCodeButtonState();
}

class _SendCodeButtonState extends State<SendCodeButton> {
  String btnTitle = '获取验证码';
  Timer? timer;
  int countDown = 60;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _startCountDown,
      child: Text(
        btnTitle,
        style: const TextStyle(
          color: Color(0xffE12F3D),
          fontSize: 14,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  Future<void> _startCountDown() async {
    if (timer?.isActive == true) {
      return;
    }
    var result = await widget.sendCode();
    if (!result) {
      return;
    }
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countDown == 0) {
        timer.cancel();
        btnTitle = '重新获取';
        countDown = 60;
        setState(() {});
      } else {
        countDown--;
        btnTitle = '$countDown s';
        setState(() {});
      }
    });
  }
}
