import 'dart:io';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/service/AuthenticatedUserObject.dart';
import 'package:diplomaticquarterapp/core/service/medical/vital_sign_service.dart';
import 'package:diplomaticquarterapp/core/viewModels/appointment_rate_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/pharmacy_module_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/toDoCountProviderModel.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/models/Authentication/check_activation_code_response.dart';
import 'package:diplomaticquarterapp/models/FamilyFiles/GetAllSharedRecordByStatusResponse.dart';
import 'package:diplomaticquarterapp/pages/DrawerPages/notifications/notifications_page.dart';
import 'package:diplomaticquarterapp/pages/landing/landing_page.dart';
import 'package:diplomaticquarterapp/pages/rateAppointment/rate_appointment_doctor.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/family_files/family_files_provider.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/widgets/text/app_texts_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../config/size_config.dart';
import '../../locator.dart';
import 'drawer_item_widget.dart';

class AppDrawer extends StatefulWidget {
  @override
  _AppDrawerState createState() => _AppDrawerState();
}

class _AppDrawerState extends State<AppDrawer> {
  @override
  void initState() {
    super.initState();
    checkUserData();
  }

  ProjectViewModel projectProvider;
  var sharedPref = new AppSharedPreferences();
  var familyFileProvider = FamilyFilesProvider();
  PharmacyModuleViewModel pharmacyModuleViewModel = locator<PharmacyModuleViewModel>();
  AuthenticatedUser user;
  AuthenticatedUser mainUser;
  AuthenticatedUserObject authenticatedUserObject =
      locator<AuthenticatedUserObject>();
  VitalSignService _vitalSignService = locator<VitalSignService>();
  AppointmentRateViewModel appointmentRateViewModel =
      locator<AppointmentRateViewModel>();
  ToDoCountProviderModel toDoProvider;
  String booldType;
  String notificationCount;
  @override
  Widget build(BuildContext context) {
    toDoProvider = Provider.of<ToDoCountProviderModel>(context);
    projectProvider = Provider.of(context);
    return SizedBox(
      width: MediaQuery.of(context).size.width * 0.75,
      child: Container(
        color: Colors.white,
        child: Drawer(
          child: Column(
            children: <Widget>[
              Expanded(
                flex: 4,
                child: ListView(
                  padding: EdgeInsets.zero,
                  children: <Widget>[
                    Container(
                      height: SizeConfig.screenHeight * .30,
                      padding: EdgeInsets.all(15),
                      child: InkWell(
                        child: Column(
                          children: <Widget>[
                            Container(
                              child:
                                  Image.asset('assets/images/DQ/logo_big.png'),
                              margin: EdgeInsets.all(
                                  SizeConfig.imageSizeMultiplier * 4),
                            ),
                            (user != null && projectProvider.isLogin)
                                ? Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        children: <Widget>[
                                          Row(
                                            children: <Widget>[
                                              Padding(
                                                  padding:
                                                      EdgeInsets.only(right: 0),
                                                  child: Icon(
                                                    Icons.account_circle,
                                                    color: Color(0xFFc5272c),
                                                    size: 28,
                                                  )),
                                              Padding(
                                                  padding:
                                                      EdgeInsets.only(right: 5),
                                                  child: AppText(
                                                    user.firstName +
                                                        ' ' +
                                                        user.lastName,
                                                    color: Color(0xFFc5272c),
                                                  ))
                                            ],
                                          ),
                                          Row(children: <Widget>[
                                            Padding(
                                                padding: EdgeInsets.only(
                                                    left: 30, right: 10),
                                                child: Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: <Widget>[
                                                    AppText(
                                                      TranslationBase.of(
                                                                  context)
                                                              .fileno +
                                                          ": " +
                                                          user.patientID
                                                              .toString(),
                                                      color: Color(0xFFc5272c),
                                                      fontSize: SizeConfig
                                                              .textMultiplier *
                                                          1.5,
                                                    ),
                                                    AppText(
                                                      booldType != null
                                                          ? 'Blood Group: ' +
                                                              booldType
                                                          : '',
                                                      fontSize: SizeConfig
                                                              .textMultiplier *
                                                          1.5,
                                                    ),
                                                  ],
                                                ))
                                          ]),
                                          Divider()
                                        ]))
                                : SizedBox(),
                          ],
                        ),
                      ),
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        (user != null && projectProvider.isLogin)
                            ? Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: <Widget>[
                                  (user.isFamily == null ||
                                          user.isFamily == false)&& projectProvider.havePrivilege(2)
                                      ? InkWell(
                                          child: DrawerItem(
                                            TranslationBase.of(context).family,
                                            Icons.group,
                                            textColor: Color(0xFFc5272c),
                                            iconColor: Color(0xFFc5272c),
                                            bottomLine: false,
                                            sideArrow: true,
                                          ),
                                          onTap: () {
                                            Navigator.of(context).pop();
                                            Navigator.of(context).pushNamed(
                                              MY_FAMILIY,
                                            );
                                          },
                                        )
                                      : SizedBox(),
                                  FutureBuilder(
                                    future: getFamilyFiles(), // async work
                                    builder: (BuildContext context,
                                        AsyncSnapshot<
                                                GetAllSharedRecordsByStatusResponse>
                                            snapshot) {
                                      switch (snapshot.connectionState) {
                                        case ConnectionState.waiting:
                                          return Padding(
                                              padding: EdgeInsets.all(10),
                                              child: Text(''));
                                        default:
                                          if (snapshot.hasError)
                                            return Padding(
                                                padding: EdgeInsets.all(10),
                                                child: Text(snapshot.error));
                                          else
                                            return Container(
                                                decoration: BoxDecoration(
                                                    border: Border(
                                                  bottom: BorderSide(
                                                    //                   <--- left side
                                                    color: Colors.grey[200],
                                                    width: 1.0,
                                                  ),
                                                )),
                                                child: Column(
                                                  children: [
                                                    user.isFamily == true
                                                        ? Container(
                                                            padding:
                                                                EdgeInsets.only(
                                                                    bottom: 5),
                                                            child: InkWell(
                                                                onTap: () {
                                                                  switchUser(
                                                                      mainUser,
                                                                      context);
                                                                },
                                                                child: Row(
                                                                  crossAxisAlignment:
                                                                      CrossAxisAlignment
                                                                          .start,
                                                                  children: <
                                                                      Widget>[
                                                                    Expanded(
                                                                      child:
                                                                          Icon(
                                                                        Icons
                                                                            .account_circle,
                                                                        color: Color(
                                                                            0xFFc5272c),
                                                                        size:
                                                                            24,
                                                                      ),
                                                                    ),
                                                                    Expanded(
                                                                        flex: 7,
                                                                        child: Column(
                                                                            crossAxisAlignment:
                                                                                CrossAxisAlignment.start,
                                                                            children: <Widget>[
                                                                              AppText(mainUser.firstName + ' ' + mainUser.lastName),
                                                                              AppText(TranslationBase.of(context).fileno + ": " + mainUser.patientID.toString()),
                                                                            ])),
                                                                  ],
                                                                )))
                                                        : SizedBox(),
                                                    Column(
                                                        mainAxisAlignment:
                                                            MainAxisAlignment
                                                                .start,
                                                        mainAxisSize:
                                                            MainAxisSize.min,
                                                        children: snapshot.data
                                                            .getAllSharedRecordsByStatusList
                                                            .map<Widget>(
                                                                (result) {
                                                          return result
                                                                      .status ==
                                                                  3
                                                              ? Container(
                                                                  padding: EdgeInsets
                                                                      .only(
                                                                          bottom:
                                                                              5),
                                                                  child: InkWell(
                                                                      onTap: () {
                                                                        switchUser(
                                                                            result,
                                                                            context);
                                                                      },
                                                                      child: Padding(
                                                                          padding: EdgeInsets.only(right: 5),
                                                                          child: Row(
                                                                            crossAxisAlignment:
                                                                                CrossAxisAlignment.start,
                                                                            children: <Widget>[
                                                                              Expanded(
                                                                                child: Icon(Icons.account_circle, color: result.responseID == user.patientID ? Color(0xFFc5272c) : Colors.black),
                                                                              ),
                                                                              Expanded(
                                                                                  flex: 7,
                                                                                  child: Padding(
                                                                                      padding: EdgeInsets.only(left: 5, right: 5),
                                                                                      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
                                                                                        AppText(result.patientName, color: result.responseID == user.patientID ? Color(0xFFc5272c) : Colors.black),
                                                                                        AppText(TranslationBase.of(context).fileno + ": " + result.responseID.toString(), color: result.responseID == user.patientID ? Color(0xFFc5272c) : Colors.black),
                                                                                      ]))),
                                                                            ],
                                                                          ))))
                                                              : SizedBox();
                                                        }).toList())
                                                  ],
                                                ));
                                      }
                                    },
                                  ),
                                  if(projectProvider.havePrivilege(1))

                                    InkWell(
                                    child: DrawerItem(
                                        TranslationBase.of(context)
                                            .arabicChange,
                                        Icons.translate),
                                    onTap: () {
                                      if (projectProvider.isArabic) {
                                        projectProvider.changeLanguage('en');
                                      } else {
                                        projectProvider.changeLanguage('ar');
                                      }
                                    },
                                  ),
                                  InkWell(
                                    child: Stack(
                                      children: [
                                        DrawerItem(
                                          TranslationBase.of(context)
                                              .notification,
                                          Icons.notifications,
                                          count: notificationCount != null
                                              ? new Container(
                                                  padding: EdgeInsets.all(4),
                                                  margin: EdgeInsets.all(2),
                                                  decoration: new BoxDecoration(
                                                    color: Colors.red,
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            20),
                                                  ),
                                                  constraints: BoxConstraints(
                                                    minWidth: 20,
                                                    minHeight: 20,
                                                  ),
                                                  child: new Text(
                                                    notificationCount,
                                                    style: new TextStyle(
                                                      color: Colors.white,
                                                      fontSize: projectProvider
                                                              .isArabic
                                                          ? 8
                                                          : 9,
                                                    ),
                                                    textAlign: TextAlign.center,
                                                  ),
                                                  //   ),
                                                )
                                              : SizedBox(),
                                        ),
                                      ],
                                    ),
                                    onTap: () {
                                      //NotificationsPage
                                      Navigator.of(context).pop();
                                      Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                              builder: (BuildContext context) =>
                                                  NotificationsPage()));
                                    },
                                  ),
                                  if(projectProvider.havePrivilege(3))
                                  InkWell(
                                    child: DrawerItem(
                                        TranslationBase.of(context).appsetting,
                                        Icons.settings_input_composite),
                                    onTap: () {
                                      Navigator.of(context).pushNamed(
                                        SETTINGS,
                                      );
                                    },
                                  ),
                                  InkWell(
                                    child: DrawerItem(
                                        TranslationBase.of(context).rateApp,
                                        Icons.star),
                                    onTap: () {
                                      if (Platform.isIOS) {
                                        launch(
                                            "https://apps.apple.com/sa/app/dr-suliaman-alhabib/id733503978");
                                      } else {
                                        launch(
                                            "https://play.google.com/store/apps/details?id=com.ejada.hmg&hl=en");
                                      }
                                    },
                                  ),
                                  InkWell(
                                    child: DrawerItem(
                                        TranslationBase.of(context).logout,
                                        Icons.lock_open),
                                    onTap: () {
                                      logout();
                                    },
                                  )
                                ],
                              )
                            : Column(
                                children: [
                                  InkWell(
                                    child: DrawerItem(
                                        TranslationBase.of(context)
                                            .loginregister,
                                        Icons.lock_open),
                                    onTap: () {
                                      login();
                                    },
                                  ),
                                  SizedBox(
                                    height: 120,
                                  ),
                                  InkWell(
                                    child: DrawerItem(
                                        TranslationBase.of(context)
                                            .arabicChange,
                                        Icons.translate),
                                    onTap: () {
                                      if (projectProvider.isArabic) {
                                        projectProvider.changeLanguage('en');
                                      } else {
                                        projectProvider.changeLanguage('ar');
                                      }
                                    },
                                  ),
                                  InkWell(
                                    child: DrawerItem(
                                        TranslationBase.of(context).appsetting,
                                        Icons.settings_input_composite),
                                    onTap: () {
                                      Navigator.of(context).pushNamed(
                                        SETTINGS,
                                      );
                                    },
                                  ),
                                  InkWell(
                                    child: DrawerItem(
                                        TranslationBase.of(context).rateApp,
                                        Icons.star),
                                    onTap: () {
                                      if (Platform.isIOS) {
                                        launch(
                                            "https://apps.apple.com/sa/app/dr-suliaman-alhabib/id733503978");
                                      } else {
                                        launch(
                                            "https://play.google.com/store/apps/details?id=com.ejada.hmg&hl=en");
                                      }
                                    },
                                  )
                                ],
                              )
                      ],
                    )
                  ],
                ),
              ),
              Expanded(
                flex: 1,
                child: Column(
                  children: <Widget>[
                    Container(
                      child: Align(
                        alignment: FractionalOffset.bottomCenter,
                        child: Container(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              Column(
                                children: <Widget>[
                                  Text(TranslationBase.of(context).poweredBy),
                                  Image.asset(
                                    'assets/images/cs_logo_container.png',
                                    width: SizeConfig.imageSizeMultiplier * 30,
                                  )
                                ],
                              ),
                              Column(
                                children: <Widget>[
                                  Image.asset(
                                    'assets/images/new-design/vidamobile.png',
                                    width: SizeConfig.imageSizeMultiplier * 25,
                                  )
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  drawerNavigator(context, routeName) {
    Navigator.of(context).pushNamed(routeName);
  }

  checkUserData() async {
    if (await this.sharedPref.getObject(USER_PROFILE) != null) {
      var data = AuthenticatedUser.fromJson(
          await this.sharedPref.getObject(USER_PROFILE));

      var data2 = AuthenticatedUser.fromJson(
          await this.sharedPref.getObject(MAIN_USER));
      booldType = await sharedPref.getString(BLOOD_TYPE);
      notificationCount = await sharedPref.getString(NOTIFICATION_COUNT);

      setState(() {
        notificationCount = notificationCount;
        this.user = data;
        this.mainUser = data2;
      });
    }
  }

  logout() async {
    authenticatedUserObject.logout();
    projectProvider.isLogin = false;
    await authenticatedUserObject.getUser();
    _vitalSignService.heightCm = "";
    _vitalSignService.weightKg = "";
    await sharedPref.clear();
    this.user = null;
    toDoProvider.setState(0, false);
    Navigator.of(context).pushNamed(HOME);
    // projectProvider.platformBridge().unRegisterHmgGeofences();
  }

  login() async {
    var data = await sharedPref.getObject(IMEI_USER_DATA);
    sharedPref.remove(REGISTER_DATA_FOR_LOGIIN);
    if (data != null) {
      Navigator.of(context).pushNamed(CONFIRM_LOGIN);
    } else {
      Navigator.of(context).pushNamed(
        WELCOME_LOGIN,
      );
    }
  }

  Future<GetAllSharedRecordsByStatusResponse> getFamilyFiles() async {
    if (user != null) {
      if (await sharedPref.getObject(FAMILY_FILE) != null) {
        // print(await sharedPref.getObject(FAMILY_FILE));
        return Future.value(GetAllSharedRecordsByStatusResponse.fromJson(
            await sharedPref.getObject(FAMILY_FILE)));
      } else {
        return familyFileProvider.getSharedRecordByStatus();
      }
    }
  }

  switchUser(user, context) {
    GifLoaderDialogUtils.showMyDialog(context);
    this
        .familyFileProvider
        .silentLoggin(user is AuthenticatedUser ? null : user,
            mainUser: user is AuthenticatedUser)
        .then((value) {
      _vitalSignService.heightCm = "";
      _vitalSignService.weightKg = "";

      loginAfter(value, context);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
      AppToast.showErrorToast(message: err);
      Navigator.of(context).pop();
    });
  }

  loginAfter(result, context) async {
    result = CheckActivationCode.fromJson(result);
    Provider.of<ProjectViewModel>(context, listen: false).setPrivilege(privilegeList: result,isLoginChild: true);
    var familyFile = await sharedPref.getObject(FAMILY_FILE);
    var currentLang = await sharedPref.getString(APP_LANGUAGE);
    var mainUser = await sharedPref.getObject(MAIN_USER);
    var bloodType = await sharedPref.getString(BLOOD_TYPE);
    this.sharedPref.clear();
    if (mainUser["PatientID"] != result.list.patientID) {
      result.list.isFamily = true;
    }
    this.sharedPref.setString(APP_LANGUAGE, currentLang);
    this.sharedPref.setString(BLOOD_TYPE, bloodType);
    this.sharedPref.setObject(MAIN_USER, mainUser);
    this.sharedPref.setObject(USER_PROFILE, result.list);
    this.sharedPref.setObject(FAMILY_FILE, familyFile);
    this.sharedPref.setObject(LOGIN_TOKEN_ID, result.logInTokenID);
    this.sharedPref.setString(TOKEN, result.authenticationTokenID);
    // Navigator.of(context).pop();
    await authenticatedUserObject.getUser(getUser: true);
    Provider.of<ProjectViewModel>(context, listen: false).user =
        authenticatedUserObject.user;
    Provider.of<ProjectViewModel>(context, listen: false)
        .setUser(authenticatedUserObject.user);
   await pharmacyModuleViewModel.generatePharmacyToken().then((value) async {
      if(pharmacyModuleViewModel.error.isNotEmpty)
        await pharmacyModuleViewModel.createUser();
    });

    appointmentRateViewModel
        .getIsLastAppointmentRatedList()
        .then((value) => {
              //getToDoCount(),
              //Utils.hideProgressDialog(),
              if (appointmentRateViewModel.isHaveAppointmentNotRate)
                {
                  Navigator.pushAndRemoveUntil(
                      context,
                      FadePage(
                        page: RateAppointmentDoctor(),
                      ),
                      (r) => false)
                }
              else
                {
                  Navigator.pushAndRemoveUntil(
                      context,
                      FadePage(
                        page: LandingPage(),
                      ),
                      (r) => false)
                }
            })
        .catchError((err) {
      print(err);
      //Utils.hideProgressDialog();
      // GifLoaderDialogUtils.hideDialog(context);
    });
  }
}
