import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/service/client/base_app_client.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.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/routes.dart';
import 'package:diplomaticquarterapp/services/family_files/family_files_provider.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/widgets/data_display/list/flexible_container.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/text/app_texts_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../config/size_config.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();
  AuthenticatedUser user;

  @override
  Widget build(BuildContext 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,
                      child: InkWell(
                        child: DrawerHeader(
                          child: Column(
                            children: <Widget>[
                              Container(
                                child: Image.asset('assets/images/logo.png'),
                                margin: EdgeInsets.all(
                                    SizeConfig.imageSizeMultiplier * 4),
                              ),
                              user != null
                                  ? Padding(
                                      padding: EdgeInsets.all(15),
                                      child: Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.start,
                                          children: <Widget>[
                                            Row(
                                              children: <Widget>[
                                                Padding(
                                                    padding: EdgeInsets.only(
                                                        right: 5),
                                                    child: Icon(
                                                      Icons.account_circle,
                                                      color: Colors.red,
                                                    )),
                                                AppText(
                                                  user.firstName +
                                                      ' ' +
                                                      user.lastName,
                                                  color: Colors.red,
                                                )
                                              ],
                                            ),
                                            Row(children: <Widget>[
                                              Padding(
                                                  padding: EdgeInsets.only(
                                                      left: 30, top: 5),
                                                  child: Column(
                                                    children: <Widget>[
                                                      AppText(
                                                        'File No:' +
                                                            user.patientID
                                                                .toString(),
                                                        color: Colors.red,
                                                        fontSize: SizeConfig
                                                                .textMultiplier *
                                                            1.5,
                                                      ),
                                                      AppText(
                                                        user.bloodGroup != null
                                                            ? 'Blood Group: ' +
                                                                user.bloodGroup
                                                            : '',
                                                        fontSize: SizeConfig
                                                                .textMultiplier *
                                                            1.5,
                                                      ),
                                                    ],
                                                  ))
                                            ])
                                          ]))
                                  : SizedBox(),
                            ],
                          ),
                        ),
                      ),
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        InkWell(
                          child: DrawerItem(
                              TranslationBase.of(context).arabicChange,
                              Icons.translate),
                          onTap: () {
                            // Navigator.of(context).pushNamed(
                            //   WELCOME_LOGIN,
                            // );
                            if (projectProvider.isArabic) {
                              projectProvider.changeLanguage('en');
                            } else {
                              projectProvider.changeLanguage('ar');
                            }
                          },
                        ),
                        user != null
                            ? Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: <Widget>[
                                  InkWell(
                                    child: DrawerItem(
                                      TranslationBase.of(context).family,
                                      Icons.group,
                                      textColor: Colors.red,
                                      iconColor: Colors.red,
                                      bottomLine: false,
                                      sideArrow: true,
                                    ),
                                    onTap: () {
                                      Navigator.of(context).pushNamed(
                                        MY_FAMILIY,
                                      );
                                    },
                                  ),
                                  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('Loading....'));
                                        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(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment.start,
                                                    mainAxisSize:
                                                        MainAxisSize.min,
                                                    children: snapshot.data
                                                        .getAllSharedRecordsByStatusList
                                                        .map<Widget>((result) {
                                                      return result.status == 3
                                                          ? Padding(
                                                              padding: EdgeInsets
                                                                  .only(
                                                                      bottom:
                                                                          5),
                                                              child: InkWell(
                                                                  onTap: () {
                                                                    switchUser(
                                                                        result,
                                                                        context);
                                                                  },
                                                                  child: Row(
                                                                    crossAxisAlignment:
                                                                        CrossAxisAlignment
                                                                            .start,
                                                                    children: <
                                                                        Widget>[
                                                                      Expanded(
                                                                        child: Icon(
                                                                            Icons.person),
                                                                      ),
                                                                      Expanded(
                                                                          flex:
                                                                              7,
                                                                          child: Column(
                                                                              crossAxisAlignment: CrossAxisAlignment.start,
                                                                              children: <Widget>[
                                                                                Text(result.patientName),
                                                                                Text('File No:' + result.iD.toString()),
                                                                              ])),
                                                                    ],
                                                                  )))
                                                          : SizedBox();
                                                    }).toList()));
                                      }
                                    },
                                  ),
                                  InkWell(
                                    child: DrawerItem(
                                        TranslationBase.of(context)
                                            .notification,
                                        Icons.notifications),
                                    onTap: () {
                                      Navigator.of(context).pushNamed(
                                        WELCOME_LOGIN,
                                      );
                                    },
                                  ),
                                  InkWell(
                                    child: DrawerItem(
                                        TranslationBase.of(context).appsetting,
                                        Icons.settings_input_composite),
                                    onTap: () {
                                      Navigator.of(context).pushNamed(
                                        WELCOME_LOGIN,
                                      );
                                    },
                                  ),
                                  InkWell(
                                    child: DrawerItem(
                                        TranslationBase.of(context).rateApp,
                                        Icons.star),
                                    onTap: () {
                                      Navigator.of(context).pushNamed(
                                        WELCOME_LOGIN,
                                      );
                                    },
                                  ),
                                  InkWell(
                                    child: DrawerItem(
                                        TranslationBase.of(context).logout,
                                        Icons.lock_open),
                                    onTap: () {
                                      logout();
                                    },
                                  )
                                ],
                              )
                            : InkWell(
                                child: DrawerItem(
                                    TranslationBase.of(context).loginregister,
                                    Icons.lock_open),
                                onTap: () {
                                  login();
                                },
                              ),
                      ],
                    )
                  ],
                ),
              ),
              Expanded(
                flex: 1,
                child: Column(
                  children: <Widget>[
                    Container(
                      // This align moves the children to the bottom
                      child: Align(
                        alignment: FractionalOffset.bottomCenter,
                        child: Container(
                          child: Column(
                            children: <Widget>[
                              Text("Powered by"),
                              Image.asset(
                                'assets/images/cs_logo_container.png',
                                width: SizeConfig.imageSizeMultiplier * 30,
                              )
                            ],
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  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));
      setState(() {
        this.user = data;
        print(this.user);
      });
    }
  }

  logout() async {
    // this.sharedPref.remove(USER_PROFILE);
    // this.sharedPref.remove(IMEI_USER_DATA);
    // this.sharedPref.remove(TOKEN);
    // this.sharedPref.remove(LOGIN_TOKEN_ID);
    await sharedPref.clear();

    this.user = null;
    Navigator.of(context).pushNamed(HOME);
  }

  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 (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) {
    Utils.showProgressDialog(context);
    this
        .familyFileProvider
        .silentLoggin(user)
        .then((value) => loginAfter(value, context));
  }

  loginAfter(result, context) {
    Utils.hideProgressDialog();
    result = CheckActivationCode.fromJson(result);
    this.sharedPref.clear();
    this.sharedPref.setObject(USER_PROFILE, result.list);
    this.sharedPref.setObject(LOGIN_TOKEN_ID, result.logInTokenID);
    this.sharedPref.setString(TOKEN, result.authenticationTokenID);
    //this.checkIfUserAgreedBefore(result),
    Navigator.of(context).pushNamed(
      HOME,
    );
  }
}
