import 'dart:async';

import 'package:fcs/domain/entities/auth_result.dart';
import 'package:fcs/domain/entities/auth_status.dart';
import 'package:fcs/pages/main/model/main_model.dart';
import 'package:fcs/pages/signin/signin_logic.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:fcs/pages/widgets/local_text.dart';
import 'package:fcs/pages/widgets/progress.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pin_input_text_field/pin_input_text_field.dart';
import 'package:provider/provider.dart';

import '../../helpers/theme.dart';

const resend_count_sec = 30;

class SmsCodePage extends StatefulWidget {
  final String phoneNumber;
  const SmsCodePage({Key key, this.phoneNumber}) : super(key: key);
  @override
  _SmsCodePageState createState() => _SmsCodePageState();
}

class _SmsCodePageState extends State<SmsCodePage> {
  bool _isLoading = false;
  String pin;
  bool allNumberEntered;
  Timer _timer;
  int _start = resend_count_sec;
  bool canResend = false;

  @override
  void initState() {
    pin = "";
    allNumberEntered = false;
    super.initState();
    startTimer();
  }

  void startTimer() {
    _timer = new Timer.periodic(
      Duration(seconds: 1),
      (t) => setState(
        () {
          if (_start < 1) {
            t.cancel();
            canResend = true;
          } else {
            _start = _start - 1;
          }
        },
      ),
    );
  }

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

  @override
  Widget build(BuildContext context) {
    return LocalProgress(
      inAsyncCall: _isLoading,
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          leading: new IconButton(
            icon: new Icon(CupertinoIcons.back),
            onPressed: () => Navigator.of(context).pop(),
          ),
          backgroundColor: primaryColor,
        ),
        body: ListView(
          padding: EdgeInsets.only(top: 5, left: 5, right: 5),
          children: <Widget>[
            Card(
              elevation: 5.0,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.only(left: 20, right: 20, top: 40),
                    child: LocalText(
                      context,
                      'sms.verify.title',
                      fontSize: 21,
                      color: primaryColor,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(
                      left: 20,
                      top: 20,
                    ),
                    child: LocalText(context, 'sms.six.digit',
                        fontSize: 15, color: labelColor),
                  ),
                  Container(
                    padding: EdgeInsets.only(left: 20),
                    child: Text(
                      widget.phoneNumber,
                      style: TextStyle(
                          color: primaryColor,
                          fontWeight: FontWeight.bold,
                          fontSize: 16),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(top: 20, left: 20, right: 20),
                    child: PinInputTextField(
                      pinLength: 6,
                      decoration: BoxLooseDecoration(
                          strokeColorBuilder: PinListenColorBuilder(
                              primaryColor, Colors.grey[400])),
                      textInputAction: TextInputAction.done,
                      autoFocus: true,
                      onChanged: _pinChange,
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(left: 20, top: 20, right: 20),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        RaisedButton(
                          onPressed: canResend ? _resend : null,
                          color: canResend ? Colors.white : Colors.grey,
                          child: LocalText(context, 'sms.resend',
                              fontSize: 16,
                              color:
                                  canResend ? primaryColor : Colors.grey[400]),
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10.0),
                              side: BorderSide(
                                  color: canResend
                                      ? primaryColor
                                      : Colors.grey[400])),
                        ),
                        InkWell(
                          onTap: allNumberEntered ? _verify : null,
                          child: CircleAvatar(
                            backgroundColor: allNumberEntered
                                ? primaryColor
                                : Colors.grey[400],
                            child: Icon(
                              Icons.check,
                              color: Colors.white,
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(
                      left: 20,
                      right: 20,
                    ),
                    child: Row(
                      children: <Widget>[
                        LocalText(
                          context,
                          'sms.resend.seconds',
                          fontSize: 15,
                          translationVariables: [_start.toString()],
                          color: primaryColor,
                        ),
                      ],
                    ),
                  ),
                  SizedBox(height: 20),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  _pinChange(pin) {
    setState(() {
      this.pin = pin;
      this.allNumberEntered = this.pin.length == 6;
    });
  }

  _resend() async {}

  _verify() async {
    setState(() {
      _isLoading = true;
    });
    try {
      AuthResult auth = await context.read<MainModel>().signin(this.pin);

      if (auth.authStatus == AuthStatus.AUTH_VERIFIED) {
        await navigateAfterAuthVerified(context);
      }
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    }
    setState(() {
      _isLoading = false;
    });
  }

  _completeResend() {
    setState(() {
      _isLoading = false;
      _start = resend_count_sec;
      canResend = false;
      startTimer();
    });
  }

  _completeVerify() {
    setState(() {
      _isLoading = false;
    });
  }
}
