import 'dart:convert';

import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/models/doctor/clinic_model.dart';
import 'package:doctor_app_flutter/models/doctor/doctor_profile_model.dart';
import 'package:doctor_app_flutter/models/doctor/profile_req_Model.dart';
import 'package:doctor_app_flutter/models/livecare/session_status_model.dart';
import 'package:doctor_app_flutter/providers/auth_provider.dart';
import 'package:doctor_app_flutter/providers/doctor_reply_provider.dart';
import 'package:doctor_app_flutter/providers/hospital_provider.dart';
import 'package:doctor_app_flutter/providers/medicine_provider.dart';
import 'package:doctor_app_flutter/providers/project_provider.dart';
import 'package:doctor_app_flutter/providers/referral_patient_provider.dart';
import 'package:doctor_app_flutter/providers/referred_patient_provider.dart';
import 'package:doctor_app_flutter/screens/medicine/medicine_search_screen.dart';
import 'package:doctor_app_flutter/util/VideoChannel.dart';
import 'package:doctor_app_flutter/util/dr_app_shared_pref.dart';
import 'package:doctor_app_flutter/util/helpers.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/user-guid/app_showcase.dart';
import 'package:doctor_app_flutter/widgets/shared/user-guid/app_showcase_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:percent_indicator/circular_percent_indicator.dart';
import 'package:provider/provider.dart';

import '../routes.dart';
import '../widgets/dashboard/dashboard_item_icons_texts.dart';
import '../widgets/dashboard/dashboard_item_texts_widget.dart';
import '../widgets/shared/app_texts_widget.dart';
import '../widgets/shared/rounded_container_widget.dart';
import 'doctor/doctor_reply_screen.dart';
import 'doctor/my_referral_patient_screen.dart';
import 'doctor/my_referred_patient_screen.dart';

DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();
Helpers helpers = Helpers();

class DashboardScreen extends StatefulWidget {
  DashboardScreen({Key key, this.title}) : super(key: key);

  final String title;
  final String iconURL = 'assets/images/dashboard_icon/';

  @override
  _DashboardScreenState createState() => _DashboardScreenState();
}

class _DashboardScreenState extends State<DashboardScreen> {
  HospitalProvider hospitalProvider;
  AuthProvider authProvider;
  bool isLoading = false;
  ProjectProvider projectsProvider;
  BuildContext myContext;

  GlobalKey _one = GlobalKey();

  @override
  Widget build(BuildContext context) {
    myContext = context;
    hospitalProvider = Provider.of(context);
    authProvider = Provider.of(context);
    projectsProvider = Provider.of(context);
    print(authProvider.doctorsClinicList);
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus) {
      currentFocus.unfocus();
    }
    return SafeArea(
      bottom: true,
      child: AppScaffold(
        isShowAppBar: false,
        isLoading: isLoading,
        body: SingleChildScrollView(
          child: SizedBox(
            height: MediaQuery.of(context).size.height * 1.3,
            child: Column(
              children: <Widget>[
                Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    mainAxisSize: MainAxisSize.max,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: Container(
                          margin: EdgeInsets.only(left: 10, top: 10),
                          child: AppText(
                            authProvider.selectedClinicName != null
                                ? authProvider.selectedClinicName
                                : '',
                            fontWeight: FontWeight.bold,
                            fontSize: SizeConfig.textMultiplier * 2.5,
                          ),
                          alignment: Alignment.centerLeft,
                        ),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        mainAxisSize: MainAxisSize.max,
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: <Widget>[
                          InkWell(
                            onTap: () async {
                              await VideoChannel.openVideoCallScreen(
                                  kToken: 'T1==cGFydG5lcl9pZD00NjgwMzIyNCZzaWc9NWRhNmExMzU4ZDViZGU3OTA5NDY4ODRhNzI4ZGUxZTRmMjZmNzcwMjpzZXNzaW9uX2lkPTFfTVg0ME5qZ3dNekl5Tkg1LU1UVTVNelk0TXpZek9EWXdNMzV1Y0V4V1lWUlZTbTVIY3k5dVdHWm1NMWxPYTNjelpIVi1mZyZjcmVhdGVfdGltZT0xNTkzNjgzNjYyJm5vbmNlPTAuODAxMzMzMzUxMDQwNzE5NSZyb2xlPXB1Ymxpc2hlciZleHBpcmVfdGltZT0xNTk2Mjc1NjYyJmluaXRpYWxfbGF5b3V0X2NsYXNzX2xpc3Q9',
                                  kSessionId: '1_MX40NjgwMzIyNH5-MTU5MzY4MzYzODYwM35ucExWYVRVSm5Hcy9uWGZmM1lOa3czZHV-fg',
                                  kApiKey: '46803224',
                                  onFailure: (String error) {},
                                  onCallEnd: () {},
                                  callNotRespond: (SessionStatusModel sessionStatusModel) {
                                    var asd ="";
                                  });


//                              showCupertinoPicker(
//                                  context: context,
//                                  actionList: authProvider.doctorsClinicList);
                            },
                            child: Container(
                                margin:
                                    EdgeInsets.only(left: 5, top: 10, right: 5),
                                child: Icon(
                                  Icons.settings,
                                  size: SizeConfig.textMultiplier * 2.5,
                                )),
                          ),
                        ],
                      ),
                      InkWell(
                        onTap: () {
                          ShowCaseWidget.of(context).startShowCase([_one]);
                        },
                        child: Container(
                            margin: EdgeInsets.only(left: 5, top: 10, right: 5),
                            child: Icon(
                              Icons.info,
                              size: SizeConfig.textMultiplier * 2.5,
                            )),
                      )
                    ]),
                Container(
                  margin: EdgeInsets.only(left: 10, top: 5),
                  child: AppText(
                    TranslationBase.of(context).todayStatistics,
                    fontWeight: FontWeight.bold,
                  ),
                  alignment: projectsProvider.isArabic
                      ? Alignment.topRight
                      : Alignment.topLeft,
                ),
                Expanded(
                  flex: 3,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: <Widget>[
                      Expanded(
                        flex: 2,
                        child: AppShowcase(
                          key: _one,
                          description: "Test User Guid",
                          onSkipClick: () {
                            ShowCaseWidget.of(context).dismiss();
                          },
                          child: RoundedContainer(
                            child: CircularPercentIndicator(
                              radius: 100,
                              animation: true,
                              animationDuration: 1200,
                              lineWidth: 7.0,
                              percent: .75,
                              center: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  AppText("38",
                                      fontWeight: FontWeight.bold,
                                      fontSize: SizeConfig.textMultiplier * 4),
                                  AppText(
                                      TranslationBase.of(context).outPatients,
                                      fontWeight: FontWeight.normal,
                                      fontSize: SizeConfig.textMultiplier * 1.1,
                                      color: Colors.grey[800]),
                                ],
                              ),
                              circularStrokeCap: CircularStrokeCap.butt,
                              backgroundColor: Colors.blueGrey[100],
                              progressColor: Colors.red,
                            ),
                          ),
                        ),
                      ),
                      Expanded(
                          flex: 2,
                          child: Padding(
                            padding: EdgeInsets.all(8),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Expanded(
                                  flex: 1,
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.stretch,
                                    children: <Widget>[
                                      Expanded(
                                        child: DashboardItemTexts(
                                          TranslationBase.of(context).arrived,
                                          "23",
                                        ),
                                      ),
                                      Expanded(
                                        child: DashboardItemTexts(
                                          TranslationBase.of(context)
                                              .notArrived,
                                          "23",
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                Expanded(
                                    child: Column(
                                  crossAxisAlignment:
                                      CrossAxisAlignment.stretch,
                                  children: <Widget>[
                                    Expanded(
                                        child: DashboardItemTexts(
                                      TranslationBase.of(context).er,
                                      "23",
                                    )),
                                    Expanded(
                                        child: DashboardItemTexts(
                                      TranslationBase.of(context).walkIn,
                                      "23",
                                    )),
                                  ],
                                )),
                              ],
                            ),
                          ))
                    ],
                  ),
                ),
                Expanded(
                  flex: 2,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: <Widget>[
                      Expanded(
                        flex: 2,
                        child: new DashboardItemIconText(
                          DoctorApp.lab_results,
                          "08",
                          TranslationBase.of(context).labResult,
                          backgroundColor: Colors.black45,
                        ),
                      ),
                      Expanded(
                          flex: 2,
                          child: new DashboardItemIconText(
                            DoctorApp.radiology,
                            "10",
                            TranslationBase.of(context).radiology,
                            backgroundColor: Colors.black45,
                          )),
                      Expanded(
                          flex: 2,
                          child: new DashboardItemIconText(
                            DoctorApp.referral,
                            "05",
                            TranslationBase.of(context).referral,
                            backgroundColor: Colors.black45,
                          )),
                    ],
                  ),
                ),
                Expanded(
                  flex: 2,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: <Widget>[
                      Expanded(
                          flex: 2,
                          child: InkWell(
                            onTap: () {},
                            child: new DashboardItemIconText(
                                DoctorApp.in_patient_white,
                                "23",
                                TranslationBase.of(context).outPatients,
                                showBorder: true,
                                backgroundColor: Colors.red[900],
                                iconColor: Colors.white),
                          )),
                      Expanded(
                          flex: 2,
                          child: new DashboardItemIconText(
                            //widget.iconURL + 'operations.svg',
                            DoctorApp.operations,
                            "23",
                            TranslationBase.of(context).inPatient,
                            showBorder: true,
                            backgroundColor: Colors.red[900],
                          )),
                    ],
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Container(
                    margin: EdgeInsets.all(10),
                    child: AppText(
                      TranslationBase.of(context).patientServices,
                      fontWeight: FontWeight.bold,
                    ),
                    alignment: Alignment.centerLeft,
                  ),
                ),
                Expanded(
                  flex: 2,
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        flex: 2,
                        child: InkWell(
                          child: DashboardItemIconText(
                            DoctorApp.search_patient,
                            "",
                            TranslationBase.of(context).searchPatient,
                            showBorder: true,
                            backgroundColor: Colors.white,
                            valueFontColor: Colors.black,
                            titleFontColor: Colors.black,
                            iconColor: Colors.black,
                            titleFontSize: SizeConfig.textMultiplier * 2,
                          ),
                          onTap: () {
                            Navigator.of(context).pushNamed(PATIENT_SEARCH);
                          },
                        ),
                      ),
                      Expanded(
                        flex: 2,
                        child: InkWell(
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => ChangeNotifierProvider(
                                  create: (_) => DoctorReplyProvider(),
                                  child: DoctorReplyScreen(),
                                ),
                              ),
                            );
                          },
                          child: DashboardItemIconText(
                            DoctorApp.message_icon,
                            "",
                            TranslationBase.of(context).doctorReply,
                            showBorder: true,
                            backgroundColor: Colors.white,
                            valueFontColor: Colors.black,
                            titleFontColor: Colors.black,
                            iconColor: Colors.black,
                            titleFontSize: SizeConfig.textMultiplier * 2,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  flex: 2,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: InkWell(
                          child: DashboardItemIconText(
                            DoctorApp.search_patient,
                            "",
                            TranslationBase.of(context).searchMedicine,
                            showBorder: true,
                            backgroundColor: Colors.white,
                            valueFontColor: Colors.black,
                            titleFontColor: Colors.black,
                            iconColor: Colors.black,
                            titleFontSize: SizeConfig.textMultiplier * 2,
                          ),
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => ChangeNotifierProvider(
                                  create: (_) => MedicineProvider(),
                                  child: MedicineSearchScreen(),
                                ),
                              ),
                            );
                          },
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: InkWell(
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => ChangeNotifierProvider(
                                  create: (_) => MyReferralPatientProvider(),
                                  child: MyReferralPatient(),
                                ),
                              ),
                            );
                          },
                          child: DashboardItemIconText(
                            DoctorApp.referral,
                            "",
                            TranslationBase.of(context).myReferralPatient,
                            showBorder: true,
                            backgroundColor: Colors.white,
                            valueFontColor: Colors.black,
                            titleFontColor: Colors.black,
                            iconColor: Colors.black,
                            titleFontSize: SizeConfig.textMultiplier * 2,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                    flex: 2,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: InkWell(
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => ChangeNotifierProvider(
                                    create: (_) => MyReferredPatientProvider(),
                                    child: MyReferredPatient(),
                                  ),
                                ),
                              );
                            },
                            child: DashboardItemIconText(
                              DoctorApp.referral,
                              "",
                              TranslationBase.of(context).myReferredPatient,
                              showBorder: true,
                              backgroundColor: Colors.white,
                              valueFontColor: Colors.black,
                              titleFontColor: Colors.black,
                              iconColor: Colors.black,
                              titleFontSize: SizeConfig.textMultiplier * 2,
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: InkWell(
                            onTap: () {
                              Navigator.of(context).pushNamed(QR_READER);
                            },
                            child: DashboardItemIconText(
                              DoctorApp.qr_code,
                              "",
                              TranslationBase.of(context).qrReader,
                              showBorder: true,
                              backgroundColor: Colors.white,
                              valueFontColor: Colors.black,
                              titleFontColor: Colors.black,
                              iconColor: Colors.black,
                              titleFontSize: SizeConfig.textMultiplier * 2,
                            ),
                          ),
                        ),
                      ],
                    )),
                Expanded(
                    flex: 2,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: InkWell(
                            onTap: () {
                              // Navigator.of(context).pushNamed(VIDEO_CALL);
                              Navigator.of(context)
                                  .pushNamed(LIVECARE_PENDING_LIST);
                            },
                            child: DashboardItemIconText(
                              DoctorApp.referral,
                              "",
                              TranslationBase.of(context).livecare,
                              showBorder: true,
                              backgroundColor: Colors.white,
                              valueFontColor: Colors.black,
                              titleFontColor: Colors.black,
                              iconColor: Colors.black,
                              titleFontSize: SizeConfig.textMultiplier * 2,
                            ),
                          ),
                        ),
                        Expanded(flex: 1, child: Container())
                      ],
                    ))
              ],
            ),
          ),
        ),
      ),
    );
  }

  showCupertinoPicker(
      {context, List<ClinicModel> actionList, decKey, onSelectFun}) {
    showModalBottomSheet(
        isDismissible: false,
        isScrollControlled: true,
        context: context,
        builder: (BuildContext builder) {
          return Container(
            // height: 500,
            height: SizeConfig.realScreenHeight * 0.4,
            color: Color(0xfff7f7f7),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                Container(
                  color: Color(0xfff7f7f7),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      CupertinoButton(
                        child: Text(
                          'Cancel'.toUpperCase(),
                          // style: TextStyle(context)
                        ),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                      CupertinoButton(
                        child: Text(
                          'Done'.toUpperCase(),
                          // style: textStyle(context),
                        ),
                        onPressed: () {
                          Navigator.pop(context);
                          // onSelectFun(cupertinoPickerIndex);
                        },
                      )
                    ],
                  ),
                ),
                Container(
                    height: SizeConfig.realScreenHeight * 0.3,
                    color: Color(0xfff7f7f7),
                    child: Column(
                      children: actionList
                          .map((e) => Container(
                                child: InkWell(
                                    onTap: () =>
                                        changeClinic(e.clinicID, context),
                                    child: Text(
                                      e.clinicName,
                                      style: TextStyle(fontSize: 15),
                                    )),
                              ))
                          .toList(),
                    ))
              ],
            ),
          );
        });
  }

  changeClinic(clinicId, BuildContext context) async {
    Navigator.pop(context);
    changeIsLoading(true);
    Map profile = await sharedPref.getObj(DOCTOR_PROFILE);
    DoctorProfileModel doctorProfile = new DoctorProfileModel.fromJson(profile);
    ProfileReqModel docInfo = new ProfileReqModel(
        doctorID: doctorProfile.doctorID,
        clinicID: clinicId,
        license: true,
        projectID: doctorProfile.projectID,
        tokenID: '',
        languageID: 2);

    // authProvider.getDocProfiles(docInfo)
    authProvider.getDocProfiles(docInfo.toJson()).then((res) async {
      changeIsLoading(false);
      sharedPref.setObj(DOCTOR_PROFILE, res['DoctorProfileList'][0]);
    }).catchError((err) {
      changeIsLoading(false);
      helpers.showErrorToast(err);
    });
  }

  changeIsLoading(bool val) {
    setState(() {
      this.isLoading = val;
    });
  }
}
