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/providers/auth_provider.dart';
import 'package:doctor_app_flutter/providers/patients_provider.dart';
import 'package:doctor_app_flutter/routes.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:provider/provider.dart';

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;

  AuthProvider 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<AuthProvider>(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();
    });
  }
}
