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/pages/BookAppointment/widgets/BranchView.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/card/rounded_container.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/others/bottom_bar.dart';
import 'package:diplomaticquarterapp/widgets/progress_indicator/app_circular_progress_Indeicator.dart';
import 'package:diplomaticquarterapp/widgets/text/app_texts_widget.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 StatefulWidget {
  @override
  _MyFamily createState() => _MyFamily();
}

class _MyFamily extends State<MyFamily> with TickerProviderStateMixin {
  final familyFileProvider = FamilyFilesProvider();
  AppSharedPreferences sharedPref = new AppSharedPreferences();
  var userID;
  TabController _tabController;

  @override
  void initState() {
    _tabController = new TabController(length: 2, vsync: this, initialIndex: 0);

    super.initState();
  }

  bool expandFlag = false;
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            bottom: TabBar(
              indicatorColor: Colors.red,
              tabs: [
                Padding(
                    padding: EdgeInsets.all(6),
                    child: AppText(
                      TranslationBase.of(context).family,
                      color: Colors.white,
                    )),
                Padding(
                    padding: EdgeInsets.all(6),
                    child: AppText(
                      TranslationBase.of(context).request,
                      color: Colors.white,
                    )),
              ],
              controller: _tabController,
            ),
            title: AppText(TranslationBase.of(context).myFamilyFiles,
                color: Colors.white)),
        body: TabBarView(
            // physics: NeverScrollableScrollPhysics(),
            children: [myFamilyDetails(context), myFamilyRequest(context)],
            controller: _tabController),
        bottomNavigationBar: BottomBarSearch());

    // AppScaffold(
    //     appBarTitle: TranslationBase.of(context).myFamilyFiles,
    //     isShowAppBar: true,
    //     body: SingleChildScrollView(
    //         child: Container(
    //             height: SizeConfig.screenHeight,
    //             width: SizeConfig.realScreenWidth,
    //             padding: EdgeInsets.all(20),
    //             child: Stack(
    //               children: <Widget>[
    //                 TabBar(
    //                   controller: _tabController,
    //                   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(
    //                   controller: _tabController,
    //                   children: [
    //                     myFamilyDetails(context),
    //                     myFamilyRequest(context)
    //                   ],
    //                 )
    //               ],
    //             ))));
  }

  Widget myFamilyDetails(context) {
    return Container(
        height: MediaQuery.of(context).size.height,
        margin: EdgeInsets.fromLTRB(20.0, 0, 20.0, 0.0),
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 4,
              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("No data found"));
                      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(
                mainAxisAlignment: MainAxisAlignment.end,
                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,
                      ))
                    ],
                  ),
                ],
              ),
            )
          ],
        ));
  }

  Widget myFamilyRequest(context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10.0),
      child: Column(
        children: <Widget>[
          // SizedBox(height: 20.0),
          RoundedContainer(
            child: ExpansionTile(
              title: Text(
                TranslationBase.of(context).userViewRequest,
                style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
              ),
              children: <Widget>[
                FutureBuilder(
                    future: getUserViewRequest(), // async work
                    builder: (BuildContext context,
                        AsyncSnapshot<dynamic> 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('No data found'));
                          else
                            return Column(
                              children: [
                                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(children: [
                                  Row(children: [
                                    Expanded(flex: 3, child: AppText('Name')),
                                    Expanded(flex: 1, child: AppText('Allow')),
                                    Expanded(flex: 1, child: AppText('Reject')),
                                  ]),
                                  Column(
                                      children: snapshot
                                          .data['GetAllPendingRecordsList']
                                          .map<Widget>((result) {
                                    return Padding(
                                        padding: EdgeInsets.all(10),
                                        child: Row(
                                          children: <Widget>[
                                            Expanded(
                                                flex: 3,
                                                child:
                                                    Text(result.patientName)),
                                            Expanded(
                                                flex: 1,
                                                child: IconButton(
                                                  icon: Icon(
                                                    Icons.check_circle,
                                                    color: Colors.black,
                                                  ),
                                                  onPressed: () {
                                                    acceptRequest(
                                                        result, context);
                                                  },
                                                )),
                                            Expanded(
                                                flex: 1,
                                                child: IconButton(
                                                  icon: Icon(
                                                    Icons.delete,
                                                    color: Colors.black,
                                                  ),
                                                  onPressed: () {
                                                    deleteRequest(
                                                        result, context);
                                                  },
                                                ))
                                          ],
                                        ));
                                  }).toList())
                                ])
                              ],
                            );
                      }
                    })
              ],
            ),
          ),
          RoundedContainer(
              child: ExpansionTile(
            title: Text(
              TranslationBase.of(context).sentRequest,
              style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
            ),
            children: <Widget>[
              FutureBuilder(
                  future: getSentRequest(), // 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('No data found'));
                        else
                          return SingleChildScrollView(
                              child: Container(
                                  height: SizeConfig.screenHeight * .3,
                                  child: ListView(
                                    children: snapshot
                                        .data.getAllSharedRecordsByStatusList
                                        .map<Widget>((result) {
                                      return Padding(
                                          padding: EdgeInsets.all(10),
                                          child: Row(
                                            children: <Widget>[
                                              Expanded(
                                                  flex: 3,
                                                  child:
                                                      Text(result.patientName)),
                                              Expanded(
                                                  flex: 2,
                                                  child: AppText(
                                                    result.statusDescription,
                                                    color: Colors.red,
                                                  )),
                                            ],
                                          ));
                                    }).toList(),
                                  )));
                    }
                  })
            ],
          )),
          RoundedContainer(
              child: ExpansionTile(
            title: Text(
              TranslationBase.of(context).userView,
              style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
            ),
            children: <Widget>[
              FutureBuilder(
                  future: getUserViewRequest(), // async work
                  builder:
                      (BuildContext context, AsyncSnapshot<dynamic> 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('No data found'));
                        else
                          return Column(
                            children: [
                              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(children: [
                                Row(children: [
                                  Expanded(flex: 3, child: AppText('Name')),
                                  Expanded(flex: 1, child: AppText('Delete')),
                                ]),
                                Column(
                                    children: snapshot
                                        .data['GetAllPendingRecordsList']
                                        .map<Widget>((result) {
                                  return Padding(
                                      padding: EdgeInsets.all(10),
                                      child: Row(
                                        children: <Widget>[
                                          Expanded(
                                              flex: 3,
                                              child: Text(result.patientName)),
                                          Expanded(
                                              flex: 1,
                                              child: IconButton(
                                                icon: Icon(
                                                  Icons.delete,
                                                  color: Colors.black,
                                                ),
                                                onPressed: () {
                                                  deleteRequest(
                                                      result, context);
                                                },
                                              )),
                                        ],
                                      ));
                                }).toList())
                              ])
                            ],
                          );
                    }
                  })
            ],
          ))
        ],
      ),
    );
  }

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

  Future getUserViewRequest() async {
    var user = await sharedPref.getObject(USER_PROFILE);
    return familyFileProvider.getUserViewRequest(user['PatientID']);
  }

  Future<GetAllSharedRecordsByStatusResponse> getSentRequest() async {
    // var user = await sharedPref.getObject(USER_PROFILE);
    return familyFileProvider.getUserSentRequest();
  }

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

  deleteRequest(result, context) {}
  acceptRequest(result, context) {}
}
