import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/core/enum/master_lookup_key.dart';
import 'package:doctor_app_flutter/core/enum/viewstate.dart';
import 'package:doctor_app_flutter/core/viewModel/SOAP_view_model.dart';
import 'package:doctor_app_flutter/models/SOAP/master_key_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:doctor_app_flutter/widgets/shared/Text.dart';
import 'package:doctor_app_flutter/widgets/shared/TextFields.dart';
import 'package:doctor_app_flutter/widgets/shared/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/divider_with_spaces_around.dart';
import 'package:doctor_app_flutter/widgets/shared/network_base_view.dart';
import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:hexcolor/hexcolor.dart';

class AddHistoryWidget extends StatefulWidget {
  final List<MasterKeyModel> myHistoryList;

  const AddHistoryWidget({Key key, this.myHistoryList}) : super(key: key);

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

class _AddHistoryWidgetState extends State<AddHistoryWidget>
    with TickerProviderStateMixin {
  PageController _controller;
  int _currentIndex = 0;

  changePageViewIndex(pageIndex) {
    _controller.jumpToPage(pageIndex);
  }

  @override
  void initState() {
    _controller = new PageController();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          margin: EdgeInsets.only(left: 10, right: 10, top: 15),
          child: TextFields(
              hintText: "Add History",
              fontSize: 13.5,
              onTapTextFields: () {
                openHistoryList(context);
              },
              readOnly: true,
              // hintColor: Colors.black,
              suffixIcon: EvaIcons.plusCircleOutline,
              suffixIconColor: AppGlobal.appPrimaryColor,
              fontWeight: FontWeight.w600,
              // controller: messageController,
              validator: (value) {
                if (value == null)
                  return TranslationBase.of(context)
                      .emptyMessage;
                else
                  return null;
              }),
        ),
        SizedBox(
          height: 20,
        ),
        Container(
          margin:
          EdgeInsets.only(left: 15, right: 15, top: 15),
          child: Column(
            children: widget.myHistoryList.map((myHistory) {
              return Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Texts(myHistory.nameEn,
                          variant: "bodyText", bold: true, color: Colors.black),
                      InkWell(
                        child: Icon(
                          FontAwesomeIcons.trash,
                          color: Colors.grey,
                          size: 20,
                        ),
                        onTap: () => removeHistory(myHistory),
                      )
                    ],
                  ),
                  SizedBox(
                    height: 20,
                  ),
                ],
              );
            }).toList(),
          ),
        )
      ],
    );
  }

  removeHistory(MasterKeyModel masterKey) {
    Iterable<MasterKeyModel> history = widget.myHistoryList.where((element) =>
        masterKey.id == element.id && masterKey.typeId == element.typeId);

    if (history.length > 0)
      setState(() {
        widget.myHistoryList.remove(history.first);
      });
  }

  openHistoryList(BuildContext context) {
    showModalBottomSheet(
        backgroundColor: Colors.white,
        isScrollControlled: true,
        context: context,
        builder: (context) {
          return AddHistoryDialog(
            changePageViewIndex: changePageViewIndex,
            controller: _controller,
            myHistoryList: widget.myHistoryList,
            addSelectedHistories: () {
              setState(() {
                Navigator.of(context).pop();
              });
            },
            removeHistory: (masterKey) => removeHistory(masterKey),
          );
        });
  }
}

class PriorityBar extends StatefulWidget {
  final Function onTap;

  const PriorityBar({Key key, this.onTap}) : super(key: key);

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

class _PriorityBarState extends State<PriorityBar> {
  int _activePriority = 0;

  List<String> _priorities = [
    "Family",
    "Surgical/Sports",
    "Medical",
  ];

  BoxDecoration containerBorderDecoration(
      Color containerColor, Color borderColor) {
    return BoxDecoration(
      color: containerColor,
      shape: BoxShape.rectangle,
      borderRadius: BorderRadius.all(Radius.circular(6)),
      border: Border.fromBorderSide(BorderSide(
        color: borderColor,
        width: 2.0,
      )),
    );
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;

    return Container(
      height: screenSize.height * 0.070,
      decoration:
          containerBorderDecoration(Color(0Xffffffff), Color(0xFFCCCCCC)),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: _priorities.map((item) {
          bool _isActive = _priorities[_activePriority] == item ? true : false;
          return Expanded(
            child: InkWell(
                child: Center(
                  child: Container(
                      height: screenSize.height * 0.070,
                      decoration: containerBorderDecoration(
                          _isActive ? HexColor("#B8382B") : Colors.white,
                          _isActive ? HexColor("#B8382B") : Colors.white),
                      child: Center(
                        child: Text(
                          item,
                          style: TextStyle(
                            fontSize: 12,
                            color: _isActive
                                ? Colors.white
                                : Colors.black, //Colors.black,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      )),
                ),
                onTap: () {
                  widget.onTap(_priorities.indexOf(item));

                  setState(() {
                    _activePriority = _priorities.indexOf(item);
                  });
                }),
          );
        }).toList(),
      ),
    );
  }
}

class AddHistoryDialog extends StatefulWidget {
  final Function changePageViewIndex;
  final PageController controller;
  final List<MasterKeyModel> myHistoryList;
  final Function addSelectedHistories;
  final Function (MasterKeyModel) removeHistory;

  const AddHistoryDialog(
      {Key key, this.changePageViewIndex, this.controller, this.myHistoryList, this.addSelectedHistories, this.removeHistory})
      : super(key: key);

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

class _AddHistoryDialogState extends State<AddHistoryDialog> {
  @override
  Widget build(BuildContext context) {
    return FractionallySizedBox(
        heightFactor: 0.7,
        child: BaseView<SOAPViewModel>(
          onModelReady: (model) async {
            if (model.historyFamilyList.length == 0) {
              await model.getMasterLookup(MasterKeysService.HistoryFamily);
            }
          },
          builder: (_, model, w) => AppScaffold(
            // baseViewModel: model,
            isShowAppBar: false,
            body: Center(
              child: Container(
                  child: FractionallySizedBox(
                widthFactor: 0.9,
                child: Column(
                  children: [
                    SizedBox(
                      height: 10,
                    ),
                    PriorityBar(onTap: (activePriority) async {
                      widget.changePageViewIndex(activePriority);
                      if(activePriority ==1) {
                        if (model.historySurgicalList.length == 0) {
                          await model.getMasterLookup(MasterKeysService.HistorySurgical);
                          await model.getMasterLookup(MasterKeysService.HistorySports);
                        }
                      }
                      if(activePriority ==2) {
                        if (model.historyMedicalList.length == 0) {
                          await model.getMasterLookup(MasterKeysService.HistoryMedical);
                        }
                      }
                    }),
                    SizedBox(
                      height: 20,
                    ),
                    Expanded(
                      child: PageView(
                        physics: NeverScrollableScrollPhysics(),
                        controller: widget.controller,
                        onPageChanged: (index) {
                          setState(() {
                            // currentIndex = index;
                          });
                        },
                        scrollDirection: Axis.horizontal,
                        children: <Widget>[
                          Container(
                            child: Column(
                              children: [
                                NetworkBaseView(
                                  baseViewModel: model,
                                  child: Container(
                                    height:
                                        MediaQuery.of(context).size.height * 0.5,
                                    child: Center(
                                        child: Container(
                                      margin: EdgeInsets.only(top: 15),
                                      decoration: BoxDecoration(
                                          borderRadius: BorderRadius.circular(12),
                                          color: Colors.white),
                                      child: ListView(
                                        children: [
                                          Column(
                                            children: model.historyFamilyList
                                                .map((historyInfo) {
                                              return Column(
                                                children: [
                                                  Row(
                                                    children: [
                                                      Checkbox(
                                                          value: isServiceSelected(
                                                              historyInfo),
                                                          activeColor:
                                                          Colors.red[800],
                                                          onChanged:
                                                              (bool newValue) {
                                                            setState(() {
                                                              if (isServiceSelected(
                                                                  historyInfo
                                                              )) {
                                                                widget
                                                                    .removeHistory(
                                                                    historyInfo
                                                                );
                                                              }
                                                              else {
                                                                widget
                                                                    .myHistoryList
                                                                    .add(
                                                                    historyInfo);
                                                              }
                                                            });
                                                          }),
                                                      Expanded(
                                                        child: Padding(
                                                          padding:
                                                              const EdgeInsets
                                                                      .symmetric(
                                                                  horizontal: 10,
                                                                  vertical: 0),
                                                          child: Texts(
                                                              historyInfo.nameEn,
                                                              variant: "bodyText",
                                                              bold: true,
                                                              color:
                                                                  Colors.black),
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                  DividerWithSpacesAround(),
                                                ],
                                              );
                                            }).toList(),
                                          ),
                                        ],
                                      ),
                                    )),
                                  ),
                                ),
                                SizedBox(
                                  height: 10,
                                ),
                                if (model.state == ViewState.Idle)
                                  AppButton(
                                    title: "Add SELECTED HISTORIES"
                                        .toUpperCase(),
                                    onPressed: () {
                                      widget.addSelectedHistories();
                                    },
                                  ),
                              ],
                            ),
                          ),
                          Container(
                            child: Column(
                              children: [
                                NetworkBaseView(
                                  baseViewModel: model,
                                  child: Container(
                                    height:
                                    MediaQuery.of(context).size.height * 0.5,
                                    child: Center(
                                        child: Container(
                                          margin: EdgeInsets.only(top: 15),
                                          decoration: BoxDecoration(
                                              borderRadius: BorderRadius.circular(12),
                                              color: Colors.white),
                                          child: ListView(
                                            children: [
                                              Column(
                                                children: model.mergeHistorySurgicalWithHistorySportList
                                                    .map((historyInfo) {
                                                  return Column(
                                                    children: [
                                                      Row(
                                                        children: [
                                                          Checkbox(
                                                              value: isServiceSelected(
                                                                  historyInfo),
                                                              activeColor:
                                                              Colors.red[800],
                                                              onChanged:
                                                                  (
                                                                  bool newValue) {
                                                                setState(() {
                                                                  if (isServiceSelected(
                                                                      historyInfo
                                                                  )) {
                                                                    widget
                                                                        .removeHistory(
                                                                        historyInfo
                                                                    );
                                                                  }
                                                                  else {
                                                                    widget
                                                                        .myHistoryList
                                                                        .add(
                                                                        historyInfo);
                                                                  }
                                                                });
                                                              }),
                                                          Expanded(
                                                            child: Padding(
                                                              padding:
                                                              const EdgeInsets
                                                                  .symmetric(
                                                                  horizontal: 10,
                                                                  vertical: 0),
                                                              child: Texts(
                                                                  historyInfo.nameEn,
                                                                  variant: "bodyText",
                                                                  bold: true,
                                                                  color:
                                                                  Colors.black),
                                                            ),
                                                          ),
                                                        ],
                                                      ),
                                                      DividerWithSpacesAround(),
                                                    ],
                                                  );
                                                }).toList(),
                                              ),
                                            ],
                                          ),
                                        )),
                                  ),
                                ),
                                SizedBox(
                                  height: 10,
                                ),
                                if (model.state == ViewState.Idle)
                                  AppButton(
                                    title: "Add SELECTED HISTORIES"
                                        .toUpperCase(),
                                    onPressed: () {
                                      widget.addSelectedHistories();
                                    },
                                  ),
                              ],
                            ),
                          ),
                          Container(
                            child: Column(
                              children: [
                                NetworkBaseView(
                                  baseViewModel: model,
                                  child: Container(
                                    height:
                                    MediaQuery.of(context).size.height * 0.5,
                                    child: Center(
                                        child: Container(
                                          margin: EdgeInsets.only(top: 15),
                                          decoration: BoxDecoration(
                                              borderRadius: BorderRadius.circular(12),
                                              color: Colors.white),
                                          child: ListView(
                                            children: [
                                              Column(
                                                children: model.historyMedicalList
                                                    .map((historyInfo) {
                                                  return Column(
                                                    children: [
                                                      Row(
                                                        children: [
                                                          Checkbox(
                                                              value: isServiceSelected(
                                                                  historyInfo),
                                                              activeColor:
                                                              Colors.red[800],
                                                              onChanged:
                                                                  (
                                                                  bool newValue) {
                                                                setState(() {
                                                                  if (isServiceSelected(
                                                                      historyInfo
                                                                  )) {
                                                                    widget
                                                                        .removeHistory(
                                                                        historyInfo
                                                                    );
                                                                  }
                                                                  else {
                                                                    widget
                                                                        .myHistoryList
                                                                        .add(
                                                                        historyInfo);
                                                                  }
                                                                });
                                                              }),
                                                          Expanded(
                                                            child: Padding(
                                                              padding:
                                                              const EdgeInsets
                                                                  .symmetric(
                                                                  horizontal: 10,
                                                                  vertical: 0),
                                                              child: Texts(
                                                                  historyInfo.nameEn,
                                                                  variant: "bodyText",
                                                                  bold: true,
                                                                  color:
                                                                  Colors.black),
                                                            ),
                                                          ),
                                                        ],
                                                      ),
                                                      DividerWithSpacesAround(),
                                                    ],
                                                  );
                                                }).toList(),
                                              ),
                                            ],
                                          ),
                                        )),
                                  ),
                                ),
                                SizedBox(
                                  height: 10,
                                ),
                                if (model.state == ViewState.Idle)
                                  AppButton(
                                    title: "Add SELECTED HISTORIES"
                                        .toUpperCase(),
                                    onPressed: () {
                                      setState(() {
                                        widget.addSelectedHistories();
                                      });
                                    },
                                  ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                  )),
            ),
          ),
        ));
  }

  isServiceSelected(MasterKeyModel masterKey) {
    Iterable<MasterKeyModel> history =
    widget
        .myHistoryList
        .where((element) =>
    masterKey.id == element.id && masterKey.typeId == element.typeId);
    if (history.length > 0) {
      return true;
    }
    return false;
  }

}
