import 'package:barcode_scan/platform_wrapper.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/models/doctor/doctor_profile_model.dart';
import 'package:doctor_app_flutter/models/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/models/patient/patient_model.dart';
import 'package:doctor_app_flutter/models/patient/topten_users_res_model.dart';
import 'package:doctor_app_flutter/providers/patients_provider.dart';
import 'package:doctor_app_flutter/util/dr_app_shared_pref.dart';
import 'package:doctor_app_flutter/util/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/widgets/shared/app_button.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/card_with_bg_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';

import '../routes.dart';

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

class _QrReaderScreenState extends State<QrReaderScreen> {
  DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();

  bool isLoading = false;
  bool isError = false;
  PatientModel patient = PatientModel(
      ProjectID: 15,
      ClinicID: 0,
      DoctorID: 1485,
      FirstName: "0",
      MiddleName: "0",
      LastName: "0",
      PatientMobileNumber: "0",
      PatientIdentificationID: "0",
      PatientID: 0,
      From: "0",
      To: "0",
      LanguageID: 2,
      stamp: "2020-03-02T13:56:39.170Z",
      IPAdress: "11.11.11.11",
      VersionID: 1.2,
      Channel: 9,
      TokenID: "@dm!n",
      SessionID: "5G0yXn0Jnq",
      IsLoginForDoctorApp: true,
      PatientOutSA: false);
  List<PatiantInformtion> patientList = [];
  String error = '';

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).qrReader,
      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,
                ),
                Button(
                  onTap: () {
                    _scanQrAndGetPatient(context);
                  },
                  title: TranslationBase.of(context).scanQr,
                  loading: isLoading,
                  icon: Image.asset('assets/images/qr_code_white.png'),
                ),
                isError
                    ? Container(
                        margin: EdgeInsets.only(top: 8),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(6.0),
                          color: Theme.of(context).errorColor.withOpacity(0.06),
                        ),
                        padding: EdgeInsets.symmetric(
                            vertical: 8.0, horizontal: 12.0),
                        child: Row(
                          children: <Widget>[
                            Expanded(
                                child: AppText(
                                    error ??
                                        TranslationBase.of(context)
                                            .errorMessage,
                                    color: Theme.of(context).errorColor)),
                          ],
                        ),
                      )
                    : Container(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  _scanQrAndGetPatient(BuildContext context) async {
    /// When give qr we will change this method to get data
    /// var result = await BarcodeScanner.scan();
    /// int patientID = get from qr result
    var result = await BarcodeScanner.scan();
    //  if (result.rawContent == "") {
    List<String> listOfParams = result.rawContent.split(',');
    String patientType = "1";
    setState(() {
      isLoading = true;
      isError = false;
      patientList = [];
    });
    String token = await sharedPref.getString(TOKEN);
//    Map profile = await sharedPref.getObj(DOCTOR_PROFILE);
//    DoctorProfileModel doctorProfile = new DoctorProfileModel.fromJson(profile);
//    patient.PatientID = 8808;
//    patient.TokenID = token;
//    patient.setDoctorID = doctorProfile.projectID;
//    patient.setClinicID = doctorProfile.clinicID;
//    patient.setProjectID = doctorProfile.projectID;
//    Provider.of<PatientsProvider>(context, listen: false);
    patient.PatientID = 8808;
    patient.TokenID = token;
    Provider.of<PatientsProvider>(context, listen: false)
        .getPatientList(patient, "1")
        .then((response) {
      if (response['MessageStatus'] == 1) {
        switch (patientType) {
          case "0":
            if (response['List_MyOutPatient'] != null) {
              setState(() {
                patientList =
                    ModelResponse.fromJson(response['List_MyOutPatient']).list;
                isLoading = false;
              });
              Navigator.of(context).pushNamed(PATIENTS_PROFILE, arguments: {
                "patient": patientList[0],
              });
            } else {
              setState(() {
                isError = true;
                isLoading = false;
              });
              DrAppToastMsg.showErrorToast('No patient');
            }
            break;
          case "1":
            if (response['List_MyInPatient'] != null) {
              setState(() {
                patientList =
                    ModelResponse.fromJson(response['List_MyInPatient']).list;
                isLoading = false;
                error = "";
              });
              Navigator.of(context).pushNamed(PATIENTS_PROFILE, arguments: {
                "patient": patientList[0],
              });
            } else {
              setState(() {
                isError = true;
                isLoading = false;
              });
              DrAppToastMsg.showErrorToast('No patient');
              break;
            }
        }
      } else {
        setState(() {
          isLoading = false;
          isError = true;
        });
        DrAppToastMsg.showErrorToast(
            response['ErrorEndUserMessage'] ?? response['ErrorMessage']);
      }
    }).catchError((error) {
      setState(() {
        isLoading = false;
      });
      helpers.showErrorToast(error);
      //DrAppToastMsg.showErrorToast(error);
    });
  }
// }
}
