import 'package:country_code_picker/country_code_picker.dart';
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/widgets/bottom_up_page_route.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:flutter/services.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:provider/provider.dart';

import '../../helpers/theme.dart';
import '../main/util.dart';
import 'sms_code_page.dart';

class SigninPage extends StatefulWidget {
  @override
  _SigninPageState createState() => _SigninPageState();
}

class _SigninPageState extends State<SigninPage> {
  bool _isLoading = false;
  String dialCode;

  TextEditingController phonenumberCtl;

  @override
  void initState() {
    super.initState();
    phonenumberCtl = new TextEditingController(text: "09");
    phonenumberCtl.selection = TextSelection.fromPosition(
        TextPosition(offset: phonenumberCtl.text.length));

    dialCode = "+95";
  }

  @override
  Widget build(BuildContext context) {
    return LocalProgress(
      inAsyncCall: _isLoading,
      child: new Scaffold(
        appBar: AppBar(
          centerTitle: true,
          leading: new IconButton(
            icon: new Icon(CupertinoIcons.back),
            onPressed: () => Navigator.of(context).pop(),
          ),
          backgroundColor: primaryColor,
        ),
        body: _buildLogin(context),
      ),
    );
  }

  Widget _buildLogin(BuildContext context) {
    return ListView(
      padding: EdgeInsets.only(top: 5, left: 15, right: 15),
      children: <Widget>[
        Container(
          padding: EdgeInsets.only(top: 40),
          child: LocalText(
            context,
            'login.title',
            fontSize: 21,
            color: primaryColor,
            fontWeight: FontWeight.bold,
          ),
        ),
        Container(
          padding: EdgeInsets.only(top: 25),
          child: LocalText(
            context,
            'login.phone',
            color: labelColor,
            fontSize: 16,
          ),
        ),
        Row(
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey[400], width: 1),
                  borderRadius: BorderRadius.all(Radius.circular(12.0))),
              child: CountryCodePicker(
                onChanged: _countryChange,
                initialSelection: dialCode,
                countryFilter: ['mm', 'us'],
                showCountryOnly: false,
                showOnlyCountryWhenClosed: false,
                alignLeft: false,
                textStyle: TextStyle(
                  fontSize: 16,
                ),
              ),
            ),
            SizedBox(
              width: 10,
            ),
            Flexible(
              child: Container(
                padding: EdgeInsets.only(top: 10, bottom: 10),
                child: TextFormField(
                  controller: phonenumberCtl,
                  cursorColor: primaryColor,
                  textAlign: TextAlign.left,
                  autofocus: true,
                  keyboardType: TextInputType.phone,
                  style: TextStyle(
                    fontSize: 18,
                  ),
                  decoration: new InputDecoration(
                    contentPadding: EdgeInsets.only(top: 8),
                    enabledBorder: UnderlineInputBorder(
                        borderSide:
                            BorderSide(color: primaryColor, width: 1.0)),
                    focusedBorder: UnderlineInputBorder(
                        borderSide:
                            BorderSide(color: primaryColor, width: 1.0)),
                  ),
                ),
              ),
            ),
          ],
        ),
        SizedBox(
          height: 20,
        ),
        Container(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              InkWell(
                onTap: () => _next(),
                child: CircleAvatar(
                  minRadius: 25,
                  backgroundColor: primaryColor,
                  child: Icon(
                    FontAwesomeIcons.arrowRight,
                    color: Colors.white,
                  ),
                ),
              )
            ],
          ),
        ),
      ],
    );
  }

  _countryChange(CountryCode countryCode) {
    setState(() {
      dialCode = countryCode.dialCode;
    });
  }

  _next() async {
    String phoneNumber = phonenumberCtl.text;
    if (phoneNumber.length < 5) {
      showMsgDialog(context, "Error", "Invalid phone number");
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      phoneNumber = phoneNumber[0] == "0"
          ? phoneNumber.replaceFirst("0", "")
          : phoneNumber;
      phoneNumber = dialCode + phoneNumber;

      AuthResult auth = await context.read<MainModel>().sendSms(phoneNumber);
      if (auth.authStatus == AuthStatus.SMS_SENT) {
        await Navigator.of(context).push(CupertinoPageRoute(
            builder: (context) => SmsCodePage(phoneNumber: phoneNumber)));
        Navigator.pop(context);
      } else if (auth.authStatus == AuthStatus.AUTH_VERIFIED) {
        await navigateAfterAuthVerified(context);
      }
      if (auth.authStatus == AuthStatus.ERROR) {
        showMsgDialog(context, "Error", auth.authErrorMsg);
      }
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    }
    setState(() {
      _isLoading = false;
    });
  }
}
