import 'package:diplomaticquarterapp/config/size_config.dart';
import 'package:diplomaticquarterapp/models/Authentication/check_activation_code_response.dart';
import 'package:diplomaticquarterapp/models/FamilyFiles/GetAllSharedRecordByStatusResponse.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/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/progress_indicator/app_circular_progress_Indeicator.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/routes.dart';

class MyFamily extends StatelessWidget {
  //bool isLoading = true;
  final familyFileProvider = FamilyFilesProvider();
  AppSharedPreferences sharedPref = new AppSharedPreferences();
  var userID;

  Widget build(BuildContext context) {
    return AppScaffold(
        appBarTitle: TranslationBase.of(context).myFamilyFiles,
        isShowAppBar: true,
        body: DefaultTabController(
            length: 2,
            child: SingleChildScrollView(
                padding: EdgeInsets.all(20),
                child: Container(
                    height: SizeConfig.realScreenHeight,
                    width: SizeConfig.realScreenWidth,
                    child: Stack(
                      children: <Widget>[
                        TabBar(
                          indicatorColor: Colors.red,
                          tabs: [
                            Padding(
                                padding: EdgeInsets.all(6),
                                child:
                                    Text(TranslationBase.of(context).family)),
                            Padding(
                                padding: EdgeInsets.all(6),
                                child:
                                    Text(TranslationBase.of(context).request)),
                          ],
                        ),
                        TabBarView(
                          children: [
                            myFamilyDetails(context),
                            myFamilyRequest(context)
                          ],
                        )
                      ],
                    )))));
  }

  Widget myFamilyDetails(context) {
    return // Padding(
        //padding: EdgeInsets.only(top: 50),
        //child:
        Column(
      // mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        Expanded(
            flex: 3,
            child: FutureBuilder(
              future: getFamilyFiles(), // async work
              builder: (BuildContext context,
                  AsyncSnapshot<GetAllSharedRecordsByStatusResponse> snapshot) {
                switch (snapshot.connectionState) {
                  case ConnectionState.waiting:
                    return Padding(
                        padding: EdgeInsets.only(top: 50),
                        child: Text('Loading....'));
                  default:
                    if (snapshot.hasError)
                      return Padding(
                          padding: EdgeInsets.all(10),
                          child: Text(snapshot.error));
                    else
                      return Padding(
                          padding: EdgeInsets.only(top: 50),
                          child: Column(children: <Widget>[
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Expanded(
                                    flex: 3,
                                    child: Text(
                                        TranslationBase.of(context).request)),
                                Expanded(
                                    flex: 2,
                                    child: Text(
                                      TranslationBase.of(context).switchUser,
                                    )),
                                Expanded(
                                    flex: 1,
                                    child: Text(
                                      TranslationBase.of(context).deleteView,
                                    )),
                              ],
                            ),
                            Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: snapshot
                                    .data.getAllSharedRecordsByStatusList
                                    .map<Widget>((result) {
                                  return result.status == 3
                                      ? Padding(
                                          padding: EdgeInsets.all(10),
                                          child: Row(
                                            children: <Widget>[
                                              Expanded(
                                                  flex: 3,
                                                  child:
                                                      Text(result.patientName)),
                                              Expanded(
                                                  flex: 2,
                                                  child: IconButton(
                                                    icon: Icon(Icons.group),
                                                    color: Colors.black,
                                                    onPressed: () {
                                                      switchUser(
                                                          result, context);
                                                    },
                                                  )),
                                              Expanded(
                                                  flex: 1,
                                                  child: IconButton(
                                                    icon: Icon(
                                                      Icons.delete,
                                                      color: Colors.black,
                                                    ),
                                                    onPressed: () {
                                                      deleteFamily(
                                                          result, context);
                                                    },
                                                  )),
                                            ],
                                          ))
                                      : SizedBox();
                                }).toList())
                          ]));
                }
              },
            )),
        Expanded(
            flex: 1,
            child: Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Expanded(
                        child: DefaultButton(
                      TranslationBase.of(context).addFamilyMember,
                      () => {
                        Navigator.of(context).pushNamed(ADD_FAMILY_MEMBER_TYPE)
                      },
                      color: Colors.grey[900],
                      textColor: Colors.white,
                    ))
                  ],
                ),
              ],
            ))
      ],
    );
  }

  addMember() {}
  Widget myFamilyRequest(context) {
    return Column(
      children: <Widget>[],
    );
  }

  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();
    }
  }

  deleteFamily(family, context) {
    ConfirmDialog dialog = new ConfirmDialog(
        context: context,
        confirmMessage: TranslationBase.of(context).removeFamilyMember,
        okText: TranslationBase.of(context).confirm,
        cancelText: TranslationBase.of(context).cancel_nocaps,
        okFunction: () => {
              removeFamily(family, context),
              ConfirmDialog.closeAlertDialog(context)
            },
        cancelFunction: () => {});
    dialog.showAlertDialog(context);
  }

  removeFamily(GetAllSharedRecordsByStatusList family, context) {
    this.userID = family.iD;
    Map<String, dynamic> request = {};
    request['ID'] = this.userID;
    request['IsActive'] = false;
    this
        .familyFileProvider
        .deativateActivateMemberFile(request)
        .then((value) => refreshFamily(context));
  }

  refreshFamily(context) {
    sharedPref.remove(FAMILY_FILE);
    (context as Element).reassemble();
  }

  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,
    );
  }
}
