import 'package:barcode_scan2/barcode_scan2.dart';
import 'package:doctor_app_flutter/config/shared_pref_kay.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/model/doctor/doctor_profile_model.dart';
import 'package:doctor_app_flutter/core/model/patient_muse/PatientSearchRequestModel.dart';
import 'package:doctor_app_flutter/core/service/AnalyticsService.dart';
import 'package:doctor_app_flutter/core/viewModel/scan_qr_view_model.dart';
import 'package:doctor_app_flutter/locator.dart';
import 'package:doctor_app_flutter/utils/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/utils/utils.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_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:flutter/cupertino.dart';
import 'package:flutter/material.dart';

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

Utils helpers = Utils();

class QrReaderScreen extends StatefulWidget {
  @override
  _QrReaderScreenState createState() => _QrReaderScreenState();
}

class _QrReaderScreenState extends State<QrReaderScreen> {
  @override
  Widget build(BuildContext context) {
    return BaseView<ScanQrViewModel>(
      builder: (_, model, w) => AppScaffold(
        baseViewModel: model,
        isShowAppBar: false,
        appBarTitle:
            TranslationBase.of(context).qr + TranslationBase.of(context).reader,
        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).scanQrCode,
                      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: "QrReaderScreen",
                        eventAction: "Scan QR",
                      );
                      _scanQrAndGetPatient(context, model);
                    },
                    icon: Image.asset('assets/images/qr_code_white.png'),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  _scanQrAndGetPatient(BuildContext context, ScanQrViewModel model) async {
    var result = (await BarcodeScanner.scan()).rawContent;
    if (result != "") {
      DoctorProfileModel doctorProfile =
          await getDoctorProfile(isGetProfile: true);
      List<String> listOfParams = result.split(',');
      int patientID = 0;
      if (listOfParams[1].length != 0) patientID = int.parse(listOfParams[1]);
      PatientSearchRequestModel patientSearchRequestModel =
          PatientSearchRequestModel(
              patientID: patientID,
              clinicID: 0,
              doctorID: 0,
              projectID: int.parse(listOfParams[0]));

      patientSearchRequestModel.loginDoctorID = doctorProfile.doctorID;

      await model
          .getInPatientList(patientSearchRequestModel, isMyInpatient: false)
          .then((d) {
        if (model.state != ViewState.ErrorLocal) {
          if (model.inPatientList.isEmpty)
            DrAppToastMsg.showErrorToast('No patient');
          else
            Navigator.of(context).pushNamed(PATIENTS_PROFILE, arguments: {
              "patient": model.inPatientList[0],
              "isInpatient": true,
              "patientType": "1",
              "arrivalType": "1",
            });
        } else {
          DrAppToastMsg.showErrorToast(model.error);
        }
      }).catchError((error) {
        Utils.showErrorToast(error.message);
      });
    }
  }

  Future<DoctorProfileModel> getDoctorProfile(
      {bool isGetProfile = false}) async {
    DoctorProfileModel? doctorProfile;
    if (isGetProfile) {
      Map<String, dynamic>? profile = await sharedPref.getObj(DOCTOR_PROFILE);
      if (profile != null) {
        doctorProfile = DoctorProfileModel.fromJson(profile);
        if (doctorProfile != null) {
          return doctorProfile;
        }
      }
    }
    if (doctorProfile == null) {
      Map<String, dynamic>? profile = await sharedPref.getObj(DOCTOR_PROFILE);
      if (profile != null) {
        doctorProfile = DoctorProfileModel.fromJson(profile);
        if (doctorProfile != null) {
          return doctorProfile;
        }
      }
      return DoctorProfileModel();
    } else {
      return doctorProfile;
    }
  }
}
