import 'dart:async';

import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/viewModel/auth_view_model.dart';
import 'package:doctor_app_flutter/routes.dart';
import 'package:doctor_app_flutter/util/helpers.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:provider/provider.dart';
Helpers helpers = Helpers();

class ShowTimerText extends StatefulWidget {
  ShowTimerText({Key key, this.model});
  final model;

  @override
  _ShowTimerTextState createState() => _ShowTimerTextState();
}

class _ShowTimerTextState extends State<ShowTimerText> {
  String timerText = (TIMER_MIN - 1).toString() + ':59';
  int min = TIMER_MIN - 1;
  int sec = 59;
  Timer _timer;

  AuthViewModel authProv;

  resendCode() {
    min = TIMER_MIN - 1;
    sec = 59;
    _timer = Timer.periodic(Duration(seconds: 1), (Timer timer) {
      if (min <= 0 && sec <= 0) {
        timer.cancel();
      } else {
        setState(() {
          sec = sec - 1;
          if (sec == 0 && min == 0) {
            Navigator.of(context).pushNamed(LOGIN);

            min = 0;
            sec = 0;
          } else if (sec == 0) {
            min = min - 1;
            sec = 59;
          }
          timerText = min.toString() + ':' + sec.toString();
        });
      }
    });
  }

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

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

  @override
  Widget build(BuildContext context) {
    authProv = Provider.of<AuthViewModel>(context);
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          InkWell(
            onTap: min != 0 || sec != 0
                ? null
                : () {
                    resendActivatioinCode();
                  },
            child: Text(
              timerText,
              style: TextStyle(
                  fontSize: 3.0 * SizeConfig.textMultiplier,
                  color: HexColor('#B8382C'),
                  fontWeight: FontWeight.bold),
            ),
          ),
        ],
      ),
    );
  }

  resendActivatioinCode() {
    authProv
        .sendActivationCodeByOtpNotificationType(widget.model)
        .then((res) => {
              // print('$value')
              if (res['MessageStatus'] == 1)
                {resendCode()}
              else
                {Helpers.showErrorToast(res['ErrorEndUserMessage'])}
            })
        .catchError((err) {
      Helpers.showErrorToast();
    });
  }
}
