import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:tangheem/api/user_api_client.dart';
import 'package:tangheem/classes/colors.dart';
import 'package:tangheem/classes/utils.dart';
import 'package:tangheem/extensions/string_extensions.dart';
import 'package:tangheem/models/country_model.dart';
import 'package:tangheem/models/general_response_model.dart';
import 'package:tangheem/ui/bottom_sheets/country_selection_bottom_sheet.dart';
import 'package:tangheem/widgets/common_textfield_widget.dart';

class RegistrationScreen extends StatefulWidget {
  static const String routeName = "/registration";

  RegistrationScreen({Key key}) : super(key: key);

  @override
  _RegistrationScreenState createState() {
    return _RegistrationScreenState();
  }
}

class _RegistrationScreenState extends State<RegistrationScreen> {
  TextEditingController _firstNameController = TextEditingController();
  TextEditingController _lastNameController = TextEditingController();
  TextEditingController _emailController = TextEditingController();
  TextEditingController _mobileNumberController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  TextEditingController _confirmPasswordController = TextEditingController();

  bool _isAccept = false;

  CountryModelData _selectedCountry;
  CountryModel _countryModel;

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

  void fetchCountryList() async {
    Utils.showLoading(context);
    try {
      _countryModel = await UserApiClient().getCountry();
      if ((_countryModel?.data?.length ?? 0) > 0) {
        _selectedCountry = _countryModel.data.first;
      }
      setState(() {});
    } catch (ex) {
      if (mounted) Utils.handleException(ex, null);
    } finally {
      Utils.hideLoading(context);
    }
  }

  void registerUser(String _firstName, String _lastName, String _email, String _password, String _countryCode, String _phone) async {
    Utils.showLoading(context);
    try {
      GeneralResponseModel model =  await UserApiClient().registerUser(_firstName, _lastName, _email, _password, _countryCode, _phone);
      if(model.message == "UserRegistration Already Exists") {
        Utils.showToast("البريد الإلكتروني مستخدم سابقا");
        Utils.hideLoading(context);
        return;
      }
      Utils.showToast("تم إنشاء الحساب بنجاح");
      Utils.hideLoading(context);
      Navigator.pop(context);
    } catch (ex) {
      if (mounted) Utils.handleException(ex, null);
      Utils.hideLoading(context);
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorConsts.secondaryWhite,
      body: SingleChildScrollView(
        padding: EdgeInsets.all(32.0),
        physics: BouncingScrollPhysics(),
        child: Container(
          width: MediaQuery.of(context).size.width,
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(8.0), color: Colors.white),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: [
              Padding(
                padding: EdgeInsets.only(top: 24, bottom: 24),
                child: SvgPicture.asset("assets/logos/tangheem_logo.svg", width: 100, height: 100),
              ),
              Text(
                "انشاء حساب جديد",
                style: TextStyle(fontSize: 22, color: ColorConsts.primaryBlue),
              ),
              Padding(
                padding: EdgeInsets.all(8),
                child: Text(
                  "قم بتعبئة بيانات طلب انشاء الحساب و ستصلك رسالة تأكيد, ومن ثم يمكنك الدخول لحسابك الجديد",
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 14, color: ColorConsts.primaryBlue, height: 1),
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 16),
                width: double.infinity,
                padding: EdgeInsets.all(32.0),
                decoration: BoxDecoration(
                  color: ColorConsts.primaryBlue,
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(8),
                    bottomRight: Radius.circular(8),
                  ),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    CommonTextFieldWidget(hint: "البريد الإلكتروني", controller: _emailController),
                    SizedBox(height: 8),
                    CommonTextFieldWidget(hint: "الاسم الأول", controller: _firstNameController),
                    SizedBox(height: 8),
                    CommonTextFieldWidget(hint: "الاسم الأخير", controller: _lastNameController),
                    SizedBox(height: 8),
                    CommonTextFieldWidget(
                      hint: _selectedCountry?.countryNameAr ?? "الدولة",
                      controller: null,
                      suffixWidget: Icon(Icons.keyboard_arrow_down, size: 18, color: ColorConsts.secondaryOrange),
                      onTap: () {
                        _selectCountry(context);
                      },
                    ),
                    SizedBox(height: 8),
                    CommonTextFieldWidget(
                      hint: " رقم الجوال${" (" + (_selectedCountry?.countryCode ?? "+9xx") + " xxxxxxxxx)"}",
                      controller: _mobileNumberController,
                      suffixWidget: Text(_selectedCountry?.countryCode ?? "", textDirection: TextDirection.ltr),
                    ),
                    SizedBox(height: 8),
                    CommonTextFieldWidget(hint: "تعيين كلمة المرور", controller: _passwordController),
                    SizedBox(height: 8),
                    CommonTextFieldWidget(hint: "تأكيد كلمة المرور", controller: _confirmPasswordController),
                    SizedBox(height: 8),
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        InkWell(
                          onTap: () {
                            setState(() {
                              _isAccept = !_isAccept;
                            });
                          },
                          child: SvgPicture.asset(_isAccept ? "assets/icons/checkOn.svg" : "assets/icons/checkOff.svg", width: 16, height: 16),
                        ),
                        SizedBox(width: 8),
                        Expanded(
                          child: Text(
                            "أقر بأني إطلعت على شروط الاستخدام و سياسية الخصوصية و أوافق عليها",
                            style: TextStyle(color: Colors.white, fontSize: 13),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 12),
                    SizedBox(
                      width: double.infinity,
                      height: 50,
                      child: TextButton(
                        onPressed: () {
                          if (_firstNameController.text.length < 1) {
                            Utils.showToast("يرجى إدخال الاسم الأول");
                            return;
                          }
                          if (_lastNameController.text.length < 1) {
                            Utils.showToast("يرجى إدخال الاسم الأخير");
                            return;
                          }
                          if (_emailController.text.length < 1) {
                            Utils.showToast("يرجى إدخال البريد الإلكتروني");
                            return;
                          }
                          if (_selectedCountry?.countryCode == null) {
                            Utils.showToast("يرجى اختيار الدولة");
                            return;
                          }
                          if (_mobileNumberController.text.length < 1) {
                            Utils.showToast("يرجى إدخال رقم الجوال");
                            return;
                          }
                          if (_passwordController.text.length < 1) {
                            Utils.showToast("يرجى إدخال كلمة المرور");
                            return;
                          }
                          if (_confirmPasswordController.text.length < 1) {
                            Utils.showToast("يرجى تأكيد كلمة المرور");
                            return;
                          }

                          if (!_emailController.text.isValidEmail()) {
                            Utils.showToast("صيغة البريد الإلكتروني خاطئة");
                            return;
                          }

                          if (_passwordController.text != _confirmPasswordController.text) {
                            Utils.showToast("كلمة المرور غير متطابقة");
                            return;
                          }

                          if (!_isAccept) {
                            Utils.showToast("الرجاء الموافقة على سياسة الخصوصية");
                            return;
                          }
                          registerUser(
                              _firstNameController.text, _lastNameController.text, _emailController.text, _passwordController.text, _selectedCountry?.countryCode, _mobileNumberController.text);
                        },
                        style: TextButton.styleFrom(
                          primary: Colors.white,
                          backgroundColor: ColorConsts.secondaryPink,
                          textStyle: TextStyle(fontSize: 16, fontFamily: "DroidKufi"),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(6.0),
                          ),
                        ),
                        child: Text("انشئ حسابك"),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _selectCountry(context) {
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
      ),
      backgroundColor: Colors.transparent,
      builder: (BuildContext bc) => CountrySelectionBottomSheet(
          countryList: _countryModel?.data ?? [],
          onSelectCountry: (country) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              setState(() {
                _selectedCountry = country;
              });
            });
          }),
    );
  }
}
