import 'package:after_layout/after_layout.dart';
import 'package:diplomaticquarterapp/config/size_config.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/requests/CreateCustomerRequestModel.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesCustomerResponseModel.dart';
import 'package:diplomaticquarterapp/core/viewModels/packages_offers/PackagesOffersViewModel.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/AnimatedTextFields.dart';
import 'package:diplomaticquarterapp/widgets/LoadingButton.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

dynamic languageID;
var emailRegex = RegExp(r'^[^\s@]+@[^\s@]+\.[^\s@]+$');

class CreateCustomerDialogPage extends StatefulWidget {
  final BuildContext context;
  CreateCustomerDialogPage({this.context});
  PackagesViewModel viewModel;

  Future<PackagesCustomerResponseModel> show() async{
    await showDialog(context: context, builder: (context ){
      return AlertDialog(content:  this, shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20)
      ), elevation: 5, );
    });
    return viewModel.service.customer;
  }

  @override
  _CreateCustomerDialogPageState createState() => _CreateCustomerDialogPageState();

}

class _CreateCustomerDialogPageState extends State<CreateCustomerDialogPage> with AfterLayoutMixin<CreateCustomerDialogPage>, TickerProviderStateMixin{
  AnimationController _loadingController;
  AnimationController _submitController;
  bool _enableInput = true;

  Interval _nameTextFieldLoadingAnimationInterval = const Interval(0, .85);

  final _phoneFocusNode = FocusNode();

  @override
  void initState() {
    _submitController = AnimationController(vsync: this, duration: Duration(milliseconds: 1000),);
    super.initState();
  }

  @override
  void afterFirstLayout(BuildContext context) async{
  }

  // Controllers
  TextEditingController _emailTextController = TextEditingController();
  TextEditingController _phoneTextController = TextEditingController();
  TextEditingController _emailPinTextController = TextEditingController();
  TextEditingController _phonePinTextController = TextEditingController();

  bool verifyPin = false;

  PackagesViewModel viewModel() => widget.viewModel;

  @override
  Widget build(BuildContext context) {

    return BaseView<PackagesViewModel>(
        allowAny: true,
        onModelReady: (model) => widget.viewModel = model,
        builder: (_, model, wi) => verifyPin ? verifyPinWidget() : userDetailWidget()
    );
  }

  Widget verifyPinWidget(){

  }


  Widget userDetailWidget(){
    return
      Container(
        width: SizeConfig.realScreenWidth * 0.8,
        height: 270,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Align(
                alignment: Alignment.center,
                child: Texts("Create Guest Customer", textAlign: TextAlign.center, fontSize: 18, fontWeight: FontWeight.bold,)
            ),
            SizedBox(height: 30,),
            AnimatedTextFormField(
              enabled: _enableInput,
              controller: _emailTextController,
              width: 100,
              loadingController: _loadingController,
              interval: _nameTextFieldLoadingAnimationInterval,
              labelText: "Email",
              prefixIcon: Icon(Icons.email),
              keyboardType: TextInputType.emailAddress,
              textInputAction: TextInputAction.next,
              onFieldSubmitted: (value) {
                FocusScope.of(context).requestFocus(_phoneFocusNode);
              },
              validator: (value){
                return (value.isEmpty || !emailRegex.hasMatch(value))
                    ? 'Invalid email!'
                    : null;
              },
            ),

            SizedBox(height: 30,),
            AnimatedTextFormField(
              enabled: _enableInput,
              controller: _phoneTextController,
              width: 100,
              loadingController: _loadingController,
              interval: _nameTextFieldLoadingAnimationInterval,
              labelText: "Mobile Number",
              prefixIcon: Icon(Icons.phone_android),
              keyboardType: TextInputType.phone,
              textInputAction: TextInputAction.next,
              onFieldSubmitted: (value) {
                FocusScope.of(context).requestFocus(_phoneFocusNode);
              },
              validator: (value){
                return (value.isEmpty || !emailRegex.hasMatch(value))
                    ? 'Invalid email!'
                    : null;
              },
            ),
            Spacer(flex: 1,),

            AnimatedButton(
              color: Theme.of(context).primaryColor,
              loadingColor: Theme.of(context).primaryColor,
              controller: _submitController,
              text: TranslationBase.of(context).done,
              onPressed: (){
                createCustomer();
              },
            )

            ,
          ],
        ),
      );
  }

  createCustomer() async{
    setState(() => _enableInput = false);

    // loading(true);
    // var request = PackagesCustomerRequestModel(email: _emailTextController.text, phoneNumber: _phoneTextController.text);
    // viewModel().service
    //     .createCustomer(request, context: context, showLoading: false)
    //     .then((value) => success())
    //     .catchError((error) => showError(error));

  }

  success() async{
    loading(false);
    await Future.delayed(Duration(seconds: 2));
    Navigator.of(context).pop();
  }

  showError(String errorMessage) async{
    loading(false);
    setState(() => _enableInput = true);
  }

  loading(bool can){
    can ? _submitController.forward() : _submitController.reverse();
  }

}
