import 'package:barcode_scan2/barcode_scan2.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/service/AnalyticsService.dart';
import 'package:doctor_app_flutter/core/viewModel/ER_sign_in/ER_sign_in_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/locator.dart';
import 'package:doctor_app_flutter/screens/patients/patient_search/patient_search_header.dart';
import 'package:doctor_app_flutter/utils/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/utils/utils.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/divider_with_spaces_around.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../base/base_view.dart';

Utils helpers = Utils();

class ErSignInScreen extends StatefulWidget {
  @override
  _ErSignInScreenState createState() => _ErSignInScreenState();
}

class _ErSignInScreenState extends State<ErSignInScreen> {
  late ProjectViewModel projectViewModel;
  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);

    return BaseView<ERSignInViewModel>(
      builder: (_, model, w) => AppScaffold(
        baseViewModel: model,
        isShowAppBar: true,
        appBar: PatientSearchHeader(
          title: "ER Sign In",
        ),
        body: Center(
          child: Container(
            margin: EdgeInsets.only(top: SizeConfig.realScreenHeight! / 7),
            child: FractionallySizedBox(
              widthFactor: 0.9,
              child: ListView(
                children: [
                  AppText(
                    TranslationBase.of(context).startScanning,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    textAlign: TextAlign.center,
                  ),
                  SizedBox(
                    height: 7,
                  ),
                  AppText(TranslationBase.of(context).scanERQrCode, fontSize: 14, fontWeight: FontWeight.w400, textAlign: TextAlign.center),
                  SizedBox(
                    height: 15,
                  ),
                  Container(
                    height: 150,
                    child: Image.asset('assets/images/qr_code.png'),
                  ),
                  SizedBox(
                    height: 35,
                  ),
                  AppButton(
                    title: TranslationBase.of(context).scanQr,
                    onPressed: () async {
                      await locator<AnalyticsService>().logEvent(
                        eventCategory: "ErSigninScreen",
                        eventAction: "Scan QR",
                      );
                      _scanQrAndGetPatient(context, model);
                    },
                    icon: Image.asset('assets/images/qr_code_white.png'),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  _scanQrAndGetPatient(BuildContext context, ERSignInViewModel model) async {
    var result = (await BarcodeScanner.scan()).rawContent;
    if (result != "") {
      try {
        List<String> listOfParams = result.split(',');
        int patientID = 0;
        if (listOfParams[0].length != 0) patientID = int.parse(listOfParams[0]);
        showMyDialog(
            context: context,
            firstAction: () {
              signInERPatient(context: context, model: model, patientId: patientID, signInType: 1);
            },
            secondAction: () {
              signInERPatient(context: context, model: model, patientId: patientID, signInType: 2);
            });
      } catch (e) {
        Utils.showErrorToast("Please Enter Valid Code");
      }
    }
  }

  signInERPatient({required BuildContext context, required ERSignInViewModel model, patientId, signInType}) async {
    GifLoaderDialogUtils.showMyDialog(context);
    await model.signInERPatient(patientId: patientId, signInType: signInType);
    if (model.state == ViewState.ErrorLocal) {
      Utils.showErrorToast(model.error);
    } else {
      /// TODO Elham* Create this in Utils
      DrAppToastMsg.showSuccesToast("Add successfully");
    }
    GifLoaderDialogUtils.hideDialog(context);
    Navigator.of(context).pop();
  }

  /// TODO  Elham* Make this as custom Dialog
  showMyDialog({
    required BuildContext context,
    required Function firstAction,
    required Function secondAction,
  }) {
    showDialog(
        context: context,
        builder: (ctx) => Center(
              child: Container(
                width: MediaQuery.of(context).size.width * 0.8,
                height: 250,
                child: AppScaffold(
                  isShowAppBar: false,
                  body: Container(
                    color: Colors.white,
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          // SizedBox(height: 20,),
                          SizedBox(
                            height: 10,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              AppText(
                                "Select option",
                                fontWeight: FontWeight.w600,
                                color: Colors.black,
                                fontSize: 16,
                              ),
                            ],
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          DividerWithSpacesAround(),
                          SizedBox(
                            height: 12,
                          ),

                          Container(
                            padding: EdgeInsets.all(20),
                            color: Colors.white,
                            child: AppText(
                              projectViewModel.isArabic ? "الرجاء اختيار الإجراء الذي تريد القيام به" : 'Please choose the action you want to do  ',
                              fontSize: 15,
                              textAlign: TextAlign.center,
                            ),
                          ),

                          SizedBox(
                            height: 8,
                          ),
                          DividerWithSpacesAround(),
                          FractionallySizedBox(
                            widthFactor: 0.75,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                ElevatedButton(
                                    child: AppText(
                                      "Sign In",
                                      fontWeight: FontWeight.w600,
                                      color: Colors.black,
                                      fontSize: 16,
                                    ), //Text("Cancel"),
                                    onPressed: () async {
                                      await firstAction();
                                    }),
                                ElevatedButton(
                                    child: AppText(
                                      "Sign Out",
                                      fontWeight: FontWeight.w600,
                                      color: Colors.black,
                                      fontSize: 16,
                                    ), //Text("Confirm", ),
                                    onPressed: () async {
                                      await secondAction();
                                    })
                              ],
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ));
  }
}
