import 'package:doctor_app_flutter/config/config.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/viewModel/PatientSearchViewModel.dart';
import 'package:doctor_app_flutter/core/viewModel/authentication_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/dashboard_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/screens/ER_singin/ER_singin_screen.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/home/dashboard_slider-item-widget.dart';
import 'package:doctor_app_flutter/screens/home/dashboard_swipe_widget.dart';
import 'package:doctor_app_flutter/screens/home/home_patient_card.dart';
import 'package:doctor_app_flutter/screens/live_care/live_care_patient_screen.dart';
import 'package:doctor_app_flutter/screens/medicine/medicine_search_screen.dart';
import 'package:doctor_app_flutter/screens/patients/In_patient/in_patient_screen.dart';
import 'package:doctor_app_flutter/screens/patients/out_patient/out_patient_screen.dart';
import 'package:doctor_app_flutter/screens/patients/patient_search/patient_search_screen.dart';
import 'package:doctor_app_flutter/screens/patients/profile/referral/referral_details/patient_referral_screen.dart';
import 'package:doctor_app_flutter/screens/pharmacy_intervention/PharmacyIntervention.dart';
import 'package:doctor_app_flutter/utils/date-utils.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/patients/profile/profile-welcome-widget.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/errors/error_message.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:doctor_app_flutter/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_zoom_videosdk/native/zoom_videosdk.dart';
import 'package:provider/provider.dart';
import 'package:sticky_headers/sticky_headers/widget.dart';

import '../../locator.dart';
import '../../utils/notification_permission_utils.dart';
import '../video_call_zoom/zoom_video_call.dart';
import '../patients/profile/soap_update/shared_soap_widgets/bottom_sheet_title.dart';
import 'label.dart';

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

  final String? title;

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

class _HomeScreenState extends State<HomeScreen> {
  bool isLoading = false;
  late ProjectViewModel projectsProvider;
  var _isInit = true;
  DoctorProfileModel profile = DoctorProfileModel();
  bool isExpanded = false;
  bool isInpatient = false;
  int sliderActiveIndex = 0;
  var clinicId;
  AuthenticationViewModel authenticationViewModel = AuthenticationViewModel();
  int colorIndex = 0;
  double width = SizeConfig.heightMultiplier! *
      (SizeConfig.isHeightVeryShort
          ? 16
          : SizeConfig.isHeightLarge
              ? 15
              : 13);

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectsProvider = Provider.of<ProjectViewModel>(context);
    authenticationViewModel = Provider.of<AuthenticationViewModel>(context);

    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus) {
      currentFocus.unfocus();
    }

    return BaseView<DashboardViewModel>(
      onModelReady: (model) async {
        var doctorProfile = await model.getDoctorProfile();
        ProjectViewModel.setVidaPlusStatus(Utils.isVidaPlusProject(projectsProvider!, doctorProfile.projectID ?? -1));
        model.startHomeScreenServices(projectsProvider, authenticationViewModel).then((value) {
          WidgetsBinding.instance.addPostFrameCallback((_) async {
            if (model.radiologyCriticalFindingModel != null) {
              print("onModelReady radiologyCriticalFindingModel!!!");
              await showRadiologyFindingDialog(model);
              if (model.isInfectiousDiseasePending) {
                showPendingInfectiousDiseaseDialog(model);
              }
            } else {
              if (model.isInfectiousDiseasePending) {
                showPendingInfectiousDiseaseDialog(model);
              }
            }
          });
          // startZoom();
        });
      },
      builder: (_, model, w) => AppScaffold(
        baseViewModel: model,
        isLoading: model.state == ViewState.BusyLocal,
        isShowAppBar: false,
        body: ListView(children: [
          Column(children: <Widget>[
            StickyHeader(
              header: Container(
                  color: Colors.grey[100],
                  padding: EdgeInsets.only(top: 10),
                  child: Stack(children: [
                    //TODO Elham* make it componet
                    Container(
                      width: 40,
                      margin: EdgeInsets.only(left: projectsProvider.isArabic ? 0 : 32, right: projectsProvider.isArabic ? 23 : 0),
                      child: IconButton(
                        icon: SvgPicture.asset('assets/images/svgs/menu.svg', height: 25, width: 10),
                        iconSize: 15,
                        color: Colors.black,
                        onPressed: () => Scaffold.of(context).openDrawer(),
                      ),
                    ),

                    Column(children: <Widget>[
                      //
                      // InkWell(onTap: (){
                      //   AppPermissionsUtils.requestVideoCallPermission(
                      //       context: context,
                      //       onTapGrant: () {
                      //         Navigator.pushNamed(
                      //           context,
                      //           "zoom-call",
                      //           arguments: CallArguments("ZoomTestHMG", "123", "Doctor", "40", "0", true),
                      //         );
                      //
                      //       });
                      //
                      // },
                      //   child: Text("Zoom Call"),
                      // ),
                      ProfileWelcomeWidget(
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Container(
                              width: MediaQuery.of(context).size.width * .6,
                              child: projectsProvider.doctorClinicsList.length > 0
                                  ? Stack(
                                      children: [
                                        DropdownButtonHideUnderline(
                                            child: DropdownButton(
                                          dropdownColor: Colors.white,
                                          iconEnabledColor: AppGlobal.appTextColor,
                                          icon: Icon(Icons.keyboard_arrow_down),
                                          isExpanded: true,
                                          value: clinicId == null ? projectsProvider.doctorClinicsList[0].clinicID : clinicId,
                                          iconSize: 25,
                                          elevation: 16,
                                          selectedItemBuilder: (BuildContext context) {
                                            return projectsProvider.doctorClinicsList.map((item) {
                                              return Row(
                                                mainAxisSize: MainAxisSize.max,
                                                mainAxisAlignment: MainAxisAlignment.end,
                                                children: <Widget>[
                                                  Column(
                                                    mainAxisAlignment: MainAxisAlignment.center,
                                                    children: [
                                                      Container(
                                                          padding: EdgeInsets.all(0),
                                                          margin: EdgeInsets.all(2),
                                                          decoration: new BoxDecoration(
                                                            color: AppGlobal.appRedColor,
                                                            borderRadius: BorderRadius.circular(20),
                                                          ),
                                                          constraints: BoxConstraints(
                                                            minWidth: 20,
                                                            minHeight: 20,
                                                          ),
                                                          child: Center(
                                                            child: AppText(
                                                              projectsProvider.doctorClinicsList.length.toString(),
                                                              color: Colors.white,
                                                              letterSpacing: -0.72,
                                                              fontWeight: FontWeight.w600,
                                                              fontSize: projectsProvider.isArabic ? 10 : 12,
                                                              textAlign: TextAlign.center,
                                                            ),
                                                          )),
                                                    ],
                                                  ),
                                                  AppText(Utils.convertToTitleCase(item.clinicName),
                                                      fontSize: 14, letterSpacing: -0.96, color: AppGlobal.appTextColor, fontWeight: FontWeight.bold, textAlign: TextAlign.end),
                                                ],
                                              );
                                            }).toList();
                                          },
                                          onChanged: (newValue) async {
                                            clinicId = newValue;
                                            GifLoaderDialogUtils.showMyDialog(context);
                                            await model.changeClinic(newValue, authenticationViewModel);
                                            GifLoaderDialogUtils.hideDialog(context);
                                            if (model.state == ViewState.ErrorLocal) {
                                              DrAppToastMsg.showErrorToast(model.error);
                                            }
                                          },
                                          items: projectsProvider.doctorClinicsList.map((item) {
                                            return DropdownMenuItem(
                                              child: AppText(
                                                Utils.convertToTitleCase(item.clinicName),
                                                fontSize: 14,
                                                letterSpacing: -0.96,
                                                color: AppGlobal.appTextColor,
                                                fontWeight: FontWeight.bold,
                                                textAlign: TextAlign.left,
                                              ),
                                              value: item.clinicID,
                                            );
                                          }).toList(),
                                        )),
                                      ],
                                    )
                                  : AppText(TranslationBase.of(context).noClinic),
                            ),
                          ],
                        ),
                        isClinic: true,
                        height: 50,
                      ),
                    ])
                  ])),
              content: Column(
                children: [
                  if (model.state != ViewState.ErrorLocal)
                    Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        model.dashboardItemsList.length > 0
                            ? DashboardSwipeWidget(
                                model.dashboardItemsList,
                                model,
                                (sliderIndex) {
                                  setState(() {
                                    sliderActiveIndex = sliderIndex;
                                  });
                                },
                              )
                            : SizedBox(),
                        model.dashboardItemsList.length > 0
                            ? FractionallySizedBox(
                                widthFactor: 0.90,
                                child: Container(
                                    child: Column(mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[
                                  SizedBox(
                                    height: 10,
                                  ),
                                  sliderActiveIndex == 1
                                      ? DashboardSliderItemWidget(model.dashboardItemsList[4])
                                      : sliderActiveIndex == 0
                                          ? DashboardSliderItemWidget(model.dashboardItemsList[3])
                                          : DashboardSliderItemWidget(model.dashboardItemsList[6]),
                                ])))
                            : SizedBox(),
                      ],
                    )
                  else
                    Container(
                        child: ErrorMessage(
                      error: model.error!,
                    )),
                  FractionallySizedBox(
                    // widthFactor: 0.90,
                    child: Container(
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.only(
                            topRight: Radius.circular(50),
                          )),
                      padding: EdgeInsets.only(left: 20, top: 10, right: 20),
                      margin: EdgeInsets.only(top: 10),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          SizedBox(
                            height: 10,
                          ),
                          Label(
                            firstLine: TranslationBase.of(context).patients,
                            secondLine: TranslationBase.of(context).services,
                          ),
                          Container(
                              height: SizeConfig.heightMultiplier! *
                                  (SizeConfig.isHeightVeryShort
                                      ? 16
                                      : SizeConfig.isHeightShort
                                          ? 14
                                          : SizeConfig.isHeightLarge
                                              ? 15
                                              : 13),
                              child: ListView(scrollDirection: Axis.horizontal, children: [
                                ...homePatientsCardsWidget(model, projectsProvider),
                              ])),
                          SizedBox(
                            height: 20,
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            )
          ]),
        ]),
      ),
    );
  }

  showRadiologyFindingDialog(DashboardViewModel model) async {
    await Utils.showConfirmationDialog(context, model.radiologyCriticalFindingModel?.notificationMesssage ?? 'test radiology', () async {
      GifLoaderDialogUtils.showMyDialog(context);
      await model.acknowledgeRadiologyCriticalFinding(model.radiologyCriticalFindingModel?.invoiceNo?.toString() ?? '', model.radiologyCriticalFindingModel?.invoiceLineItemNo?.toString() ?? '');
      GifLoaderDialogUtils.hideDialog(context);
      Navigator.of(context).pop();
    }, isShowCancelButton: false);
  }

  showPendingInfectiousDiseaseDialog(DashboardViewModel model) {
    // Utils.showConfirmationDialog(
    //     context, TranslationBase.of(context).youHavePendingInterventions,
    //     () async {
    //   Navigator.pop(context);
    //   Navigator.push(
    //       context,
    //       MaterialPageRoute(
    //         builder: (context) => PharmacyIntervention(),
    //         settings: RouteSettings(name: 'PharmacyIntervention'),
    //       ));
    // }, isShowCancelButton: false);

    _showErrorBottomSheet(context, TranslationBase.of(context).youHavePendingInterventions);
  }

  List<Widget> homePatientsCardsWidget(DashboardViewModel model, projectsProvider) {
    colorIndex = 0;

    List<LinearGradient> backgroundColors = [];
    backgroundColors.add(LinearGradient(begin: Alignment(-1.0, -2.0), end: Alignment(1.0, 2.0), colors: [
      AppGlobal.appRedColor,
      Color(0xFFAD3B3B),
    ])); //AppGlobal.appRedColor;
    backgroundColors.add(LinearGradient(begin: Alignment.center, end: Alignment.center, colors: [
      Color(0xFFC9C9C9),
      Color(0xFFC9C9C9),
    ]));
    backgroundColors.add(LinearGradient(begin: Alignment.center, end: Alignment.center, colors: [Color(0xFF71787E), AppGlobal.appTextColor]));
    List<Color> backgroundIconColors = [];
    backgroundIconColors.add(Colors.white12);
    backgroundIconColors.add(Colors.white38);
    backgroundIconColors.add(Colors.white10);
    List<Color> textColors = [];
    textColors.add(Colors.white);
    textColors.add(Color(0xFF353E47));
    textColors.add(Colors.white);

    List<HomePatientCard> patientCards = [];

    if (model.hasVirtualClinic) {
      patientCards.add(HomePatientCard(
        gradient: backgroundColors[colorIndex],
        backgroundIconColor: backgroundIconColors[colorIndex],
        cardIcon: DoctorApp.livecare,
        textColor: textColors[colorIndex],
        iconSize: 21,
        text: "${TranslationBase.of(context).liveCare}\n${TranslationBase.of(context).patients}",
        onTap: () {
          // TODO MOSA TEST
          // PatiantInformtion patient = PatiantInformtion(
          //   patientStatusType: 43,
          //   episodeNo: 0,
          //   vcId: 42342,
          //   fullName: "mosa test",
          //   dateofBirth: "2000-05-01 10:42:35.790004"
          // );
          // Navigator.of(context).pushNamed(PATIENTS_PROFILE, arguments: {
          //   "patient": patient,
          //   "patientType": "0",
          //   "isSearch": false,
          //   "isInpatient": false,
          //   "arrivalType": "0",
          //   "isSearchAndOut": false,
          //   "isFromLiveCare": true,
          // });
          Navigator.push(
            context,
            FadePage(
              page: LiveCarePatientScreen(),
            ),
          );
        },
      ));
      changeColorIndex();
    }

    patientCards.add(HomePatientCard(
      gradient: backgroundColors[colorIndex],
      backgroundIconColor: backgroundIconColors[colorIndex],
      cardIcon: DoctorApp.qr_reader,
      textColor: textColors[colorIndex],
      text: "ER sign In",
      onTap: () {
        Navigator.push(
          context,
          FadePage(
            page: ErSignInScreen(),
          ),
        );
      },
    ));
    changeColorIndex();

    if (model.doctorProfile != null) {
      patientCards.add(
          HomePatientCard(
        gradient: backgroundColors[colorIndex],
        backgroundIconColor: backgroundIconColors[colorIndex],
        cardIcon: DoctorApp.inpatient,
        textColor: textColors[colorIndex],
        text: TranslationBase.of(context).myInPatient,
        onTap: () {
          locator<PatientSearchViewModel>().flushSelectedDates();
          Navigator.push(
            context,
            FadePage(
              page: InPatientScreen(
                specialClinic: model.getSpecialClinic(clinicId ?? projectsProvider.doctorClinicsList[0].clinicID),
              ),
            ),
          );
        },
      ));
      changeColorIndex();
    }

    if (model.isInfectiousDiseaseConsultant) {
      patientCards.add(HomePatientCard(
        gradient: backgroundColors[2],
        backgroundIconColor: backgroundIconColors[2],
        cardIcon: DoctorApp.search_medicines,
        textColor: textColors[2],
        text: TranslationBase.of(context).interventionPharmacyApproval,
        fontSize: SizeConfig.getTextMultiplierBasedOnWidth(width: width) * (SizeConfig.isHeightVeryShort ? 10 : 9),
        onTap: () {
          if (!model.isInfectiousDiseaseConsultant) {
            DrAppToastMsg.showErrorToast(TranslationBase.of(context).unableToPerformTheAction);
          }
          Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => PharmacyIntervention(),
                settings: RouteSettings(name: 'PharmacyIntervention'),
              ));
        },
      ));
      //TODO Keep commented
      // patientCards.add(HomePatientCard(
      //   gradient: backgroundColors[colorIndex],
      //   backgroundIconColor: backgroundIconColors[colorIndex],
      //   //TODO Elham* match the of the icon
      //   cardIcon: DoctorApp.arrival_patients,
      //   textColor: textColors[colorIndex],
      //   text: TranslationBase.of(context).registerNewPatient,
      //   onTap: () {
      //     Navigator.push(
      //       context,
      //       FadePage(
      //         page: RegisterPatientPage(),
      //       ),
      //     );
      //   },
      // ));
      changeColorIndex();
    }

    patientCards.add(HomePatientCard(
      gradient: backgroundColors[colorIndex],
      backgroundIconColor: backgroundIconColors[colorIndex],
      cardIcon: DoctorApp.arrival_patients,
      textColor: textColors[colorIndex],
      text: TranslationBase.of(context).myOutPatient_2lines,
      onTap: () {
        String date = AppDateUtils.convertDateToFormat(DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day), 'yyyy-MM-dd');
        locator<PatientSearchViewModel>().flushSelectedDates();
        Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => OutPatientsScreen(
                patientSearchRequestModel: PatientSearchRequestModel(from: date, to: date, doctorID: authenticationViewModel.doctorProfile!.doctorID),
              ),
              settings: RouteSettings(name: 'OutPatientsScreen'),
            ));
      },
    ));
    changeColorIndex();

    patientCards.add(HomePatientCard(
      gradient: backgroundColors[colorIndex],
      backgroundIconColor: backgroundIconColors[colorIndex],
      cardIcon: DoctorApp.referral_1,
      textColor: textColors[colorIndex],
      text: TranslationBase.of(context).myPatientsReferral,
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => PatientReferralScreen(),
            settings: RouteSettings(name: 'PatientReferralScreen'),
          ),
        );
      },
    ));
    changeColorIndex();

    patientCards.add(HomePatientCard(
      gradient: backgroundColors[colorIndex],
      backgroundIconColor: backgroundIconColors[colorIndex],
      cardIcon: DoctorApp.search,
      textColor: textColors[colorIndex],
      text: TranslationBase.of(context).searchPatientDashBoard,
      onTap: () {
        Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => PatientSearchScreen(),
              settings: RouteSettings(name: 'PatientSearchScreen'),
            ));
      },
    ));
    changeColorIndex();

    patientCards.add(HomePatientCard(
      gradient: backgroundColors[colorIndex],
      backgroundIconColor: backgroundIconColors[colorIndex],
      cardIcon: DoctorApp.search_medicines,
      textColor: textColors[colorIndex],
      text: TranslationBase.of(context).searchMedicineDashboard,
      onTap: () {
        Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => MedicineSearchScreen(),
              settings: RouteSettings(name: 'MedicineSearchScreen'),
            ));
      },
    ));
    changeColorIndex();

    return [...List.generate(patientCards.length, (index) => patientCards[index]).toList()];
  }

  changeColorIndex() {
    colorIndex++;
    if (colorIndex > 2) {
      colorIndex = 0;
    }
  }

  void _showErrorBottomSheet(BuildContext context, String errorMessage) {
    showModalBottomSheet(
      isDismissible: true,
      enableDrag: false,
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      backgroundColor: Colors.red[50],
      // Light red background
      builder: (context) {
        return Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Icon(Icons.error_outline, color: Colors.red, size: 40),
                  InkWell(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Icon(
                        Icons.close,
                        color: Colors.red,
                      ),
                    ),
                  )
                ],
              ),
              const SizedBox(height: 10),
              Text(
                TranslationBase.of(context).pharmacyIntervention,
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.red),
              ),
              const SizedBox(height: 25),
              Text(
                errorMessage,
                style: TextStyle(fontSize: 16, color: Colors.black87),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 15),
              SizedBox(
                  width: SizeConfig.realScreenWidth! * .4,
                  child: AppButton(
                    color: Colors.green,
                    onPressed: () => {
                      //   Navigator.pop(context);
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => PharmacyIntervention(),
                            settings: RouteSettings(name: 'PharmacyIntervention'),
                          ))
                    },
                    title: TranslationBase.of(context).open,
                  )),
            ],
          ),
        );
      },
    );
  }

  void startZoom() {
    var zoom = ZoomVideoSdk();
    InitConfig initConfig = InitConfig(
      domain: "zoom.us",
      enableLog: true,
    );
    zoom.initSdk(initConfig);
  }
}
