import 'package:diplomaticquarterapp/core/viewModels/dashboard_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/text/app_texts_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ProfileSettings extends StatefulWidget {
  @override
  _ProfileSettings createState() => _ProfileSettings();
}

class _ProfileSettings extends State<ProfileSettings> with TickerProviderStateMixin {
  bool smsAlert = true;
  bool emailAlert = true;
  int language = 1;
  final authService = new AuthProvider();
  TextEditingController emergencyContact = new TextEditingController();
  TextEditingController emailController = new TextEditingController();
  TextEditingController emergencyContactName = new TextEditingController();
  ProjectViewModel projectProvider;

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

  Widget build(BuildContext context) {
    projectProvider = Provider.of(context);
    return BaseView<DashboardViewModel>(
      onModelReady: (model) => {getSettings()},
      builder: (_, model, wi) => Container(
        child: model.user != null
            ? Column(
                children: [
                  Expanded(
                    child: SingleChildScrollView(
                      child: Padding(
                        padding: const EdgeInsets.only(left: 21, right: 21, top: 21),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              decoration: cardRadius(8),
                              margin: EdgeInsets.zero,
                              child: Padding(
                                padding: const EdgeInsets.all(12.0),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Text(
                                      TranslationBase.of(context).fileNo + ": ",
                                      style: TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.w600,
                                        letterSpacing: -0.64,
                                      ),
                                    ),
                                    Text(
                                      model.user.patientID.toString(),
                                      style: TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.w600,
                                        letterSpacing: -0.64,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            mHeight(12),
                            Text(
                              TranslationBase.of(context).languageSetting,
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                                letterSpacing: -0.64,
                              ),
                            ),
                            Text(
                              TranslationBase.of(context).selectLanguage,
                              style: TextStyle(
                                fontSize: 12,
                                fontWeight: FontWeight.w600,
                                letterSpacing: -0.48,
                              ),
                            ),
                            Row(
                              children: [
                                Expanded(
                                  child: Row(
                                    children: [
                                      new Radio(
                                        value: 2,
                                        groupValue: language,
                                        onChanged: (value) {
                                          setState(() {
                                            language = value;
                                          });
                                        },
                                      ),
                                      Text(
                                        TranslationBase.of(context).english,
                                        style: TextStyle(
                                          fontSize: 12,
                                          letterSpacing: -0.48,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                Expanded(
                                  child: Row(
                                    children: [
                                      Radio(
                                        value: 1,
                                        groupValue: language,
                                        onChanged: (value) {
                                          setState(() {
                                            language = value;
                                          });
                                        },
                                      ),
                                      Text(
                                        TranslationBase.of(context).arabic,
                                        style: TextStyle(
                                          fontSize: 12,
                                          letterSpacing: -0.48,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                            mHeight(12),
                            Text(
                              TranslationBase.of(context).alert,
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                                letterSpacing: -0.64,
                              ),
                            ),
                            Text(
                              TranslationBase.of(context).recAlert,
                              style: TextStyle(
                                fontSize: 12,
                                fontWeight: FontWeight.w600,
                                letterSpacing: -0.48,
                              ),
                            ),
                            Row(
                              children: [
                                Checkbox(
                                  value: emailAlert,
                                  onChanged: (value) {
                                    setState(() {
                                      emailAlert = value;
                                    });
                                  },
                                  activeColor: CustomColors.accentColor,
                                ),
                                Text(
                                  TranslationBase.of(context).emailAlert,
                                  style: TextStyle(
                                    fontSize: 12,
                                    letterSpacing: -0.48,
                                  ),
                                ),
                              ],
                            ),
                            Row(
                              children: [
                                Checkbox(
                                  value: smsAlert,
                                  onChanged: (value) {
                                    setState(() {
                                      smsAlert = value;
                                    });
                                  },
                                  activeColor: CustomColors.accentColor,
                                ),
                                Text(
                                  TranslationBase.of(context).smsAlert,
                                  style: TextStyle(
                                    fontSize: 12,
                                    letterSpacing: -0.48,
                                  ),
                                ),
                              ],
                            ),
                            mHeight(16),
                            Text(
                              TranslationBase.of(context).contactInfo,
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                                letterSpacing: -0.64,
                              ),
                            ),
                            mHeight(12),
                            inputWidget(TranslationBase.of(context).email, "", emailController),
                            mHeight(8),
                            inputWidget(TranslationBase.of(context).emergencyName, "", emergencyContactName),
                            mHeight(8),
                            inputWidget(TranslationBase.of(context).emergencyContact, "", emergencyContact),
                            mHeight(10),
                            // InkWell(
                            //   onTap: () {
                            //     deactivateAccount();
                            //   },
                            //   child: Text(
                            //     TranslationBase.of(context).deleteAccount,
                            //     style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, letterSpacing: -0.64, color: Color(0xffD02127), decoration: TextDecoration.underline),
                            //   ),
                            // ),
                            mHeight(8),
                          ],
                        ),
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.all(12),
                    color: Colors.white,
                    child: Flex(
                      direction: Axis.horizontal,
                      children: <Widget>[
                        Expanded(
                          child: DefaultButton(
                            TranslationBase.of(context).deleteAccount,
                            () {
                              deactivateAccount();
                            },
                          ),
                        ),
                        mWidth(12),
                        Expanded(
                          child: DefaultButton(
                            TranslationBase.of(context).save,
                            () {
                              saveSettings();
                            },
                            color: CustomColors.green,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              )
            : Center(
                child: AppText(TranslationBase.of(context).loginToUseService),
              ),
      ),
    );
  }

  Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller, {String prefix, bool isEnable = true, bool hasSelection = false}) {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        color: Colors.white,
        border: Border.all(
          color: Color(0xffefefef),
          width: 1,
        ),
      ),
      child: InkWell(
        onTap: hasSelection ? () {} : null,
        child: Row(
          children: [
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _labelText,
                    style: TextStyle(
                      fontSize: 11,
                      fontWeight: FontWeight.w600,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                  ),
                  TextField(
                    enabled: isEnable,
                    scrollPadding: EdgeInsets.zero,
                    keyboardType: TextInputType.emailAddress,
                    controller: _controller,
                    // onChanged: (value) => {validateForm()},
                    style: TextStyle(
                      fontSize: 14,
                      height: 21 / 14,
                      fontWeight: FontWeight.w400,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                    decoration: InputDecoration(
                      isDense: true,
                      hintText: _hintText,
                      hintStyle: TextStyle(
                        fontSize: 14,
                        height: 21 / 14,
                        fontWeight: FontWeight.w400,
                        color: Color(0xff575757),
                        letterSpacing: -0.56,
                      ),
                      prefixIconConstraints: BoxConstraints(minWidth: 50),
                      prefixIcon: prefix == null
                          ? null
                          : Text(
                              "+" + prefix,
                              style: TextStyle(
                                fontSize: 14,
                                height: 21 / 14,
                                fontWeight: FontWeight.w500,
                                color: Color(0xff2E303A),
                                letterSpacing: -0.56,
                              ),
                            ),
                      contentPadding: EdgeInsets.zero,
                      border: InputBorder.none,
                      focusedBorder: InputBorder.none,
                      enabledBorder: InputBorder.none,
                    ),
                  ),
                ],
              ),
            ),
            if (hasSelection) Icon(Icons.keyboard_arrow_down_outlined),
          ],
        ),
      ),
    );
  }

  deactivateAccount() {
    ConfirmDialog dialog = new ConfirmDialog(
        context: context,
        confirmMessage: TranslationBase.of(context).deactivateAccount,
        okText: TranslationBase.of(context).yes,
        cancelText: TranslationBase.of(context).no,
        okFunction: () {
          Navigator.of(context).pop();
          callDeactivateAccountAPI();
        },
        cancelFunction: () => {});
    dialog.showAlertDialog(context);
  }

  callDeactivateAccountAPI() {
    GifLoaderDialogUtils.showMyDialog(context);
    Map<String, dynamic> request = {};
    request["IsActive"] = false;
    request["PatientIdentificationID"] = projectProvider.user.patientIdentificationNo;
    request["PatientMobileNumber"] = Utils.getPhoneNumberWithoutZero(projectProvider.user.mobileNumber);
    authService.deactivateAccount(request, false).then((result) {
      AppToast.showSuccessToast(message: TranslationBase.of(context).accountDeactivated);
      GifLoaderDialogUtils.hideDialog(context);
    });
  }

  getSettings() {
    authService.getSettings().then((result) => {setValue(result["PateintInfoForUpdateList"][0])});
  }

  setValue(value) {
    setState(() {
      this.language = int.parse(value["PreferredLanguage"]);
      this.emailAlert = value["IsEmailAlertRequired"];
      this.smsAlert = value["IsSMSAlertRequired"];
      this.emailController.text = value["EmailAddress"];
      this.emergencyContact.text = value["EmergencyContactNo"];
      this.emergencyContactName.text = value["EmergencyContactName"];
    });
  }

  saveSettings() {
    GifLoaderDialogUtils.showMyDialog(context);
    Map<String, dynamic> request = {};
    request["EmailAddress"] = this.emailController.text;
    request["EmergencyContactName"] = this.emergencyContactName.text;
    request["EmergencyContactNo"] = this.emergencyContact.text;
    request["IsEmailAlertRequired"] = this.emailAlert;
    request["IsSMSAlertRequired"] = this.smsAlert;
    request["PreferredLanguage"] = this.language.toString();
    authService.saveSettings(request).then((result) {
      AppToast.showSuccessToast(message: TranslationBase.of(context).profileUpdate);
      GifLoaderDialogUtils.hideDialog(context);
      AuthenticatedUser authUser = projectProvider.user;
      authUser.emailAddress = this.emailController.text;
      projectProvider.setUser(authUser);
    });
  }
}
