import 'package:doctor_app_flutter/core/enum/master_lookup_key.dart';
import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/viewModel/SOAP_view_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/master_key_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/selected_items/my_selected_history.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/soap_utils.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/widgets/bottom_sheet/custom_bottom_sheet_container.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/master_key_checkbox_search_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/network_base_view.dart';
import 'package:flutter/material.dart';

import '../../shared_soap_widgets/bottom_sheet_title.dart';
import 'priority_bar.dart';

class AddHistoryDialog extends StatefulWidget {
  final Function? changePageViewIndex;
  final PageController? controller;
  final List<MySelectedHistory>? 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: 1,
        child: BaseView<SOAPViewModel>(
          onModelReady: (model) async {
            if (model.historyFamilyList.length == 0) {
              await model.getMasterLookup(MasterKeysService.HistoryFamily);
            }

            if (model.historySurgicalList.length == 0) {
              await model.getMasterLookup(MasterKeysService.HistorySurgical);
              await model.getMasterLookup(MasterKeysService.HistorySports);
            }

            if (model.historyMedicalList.length == 0) {
              await model.getMasterLookup(MasterKeysService.HistoryMedical);
            }
          },
          builder: (_, model, w) => AppScaffold(
            baseViewModel: model,
            isShowAppBar: true,
            appBar: BottomSheetTitle(title: TranslationBase.of(context).addHistory),
            body: Center(
              child: Container(
                  child: Column(
                children: [
                  SizedBox(
                    height: 10,
                  ),
                  PriorityBar(onTap: (activePriority) async {
                    widget.changePageViewIndex!(activePriority);
                  }),
                  SizedBox(
                    height: 20,
                  ),
                  Expanded(
                    child: FractionallySizedBox(
                      widthFactor: 0.9,
                      child: PageView(
                        physics: NeverScrollableScrollPhysics(),
                        controller: widget.controller,
                        onPageChanged: (index) {
                          setState(() {});
                        },
                        scrollDirection: Axis.horizontal,
                        children: <Widget>[
                          NetworkBaseView(
                            baseViewModel: model,
                            child: MasterKeyCheckboxSearchWidget(
                              model: model,
                              masterList: model.historyFamilyList,
                              removeHistory: (history) {
                                setState(() {
                                  widget.removeHistory!(history);
                                });
                              },
                              addHistory: (history) {
                                setState(() {
                                  createAndAddHistory(history);
                                });
                              },
                              addSelectedHistories: () {
                                widget.addSelectedHistories!();
                              },
                              isServiceSelected: (master) => isServiceSelected(master),
                            ),
                          ),
                          NetworkBaseView(
                            baseViewModel: model,
                            child: MasterKeyCheckboxSearchWidget(
                              model: model,
                              masterList: model.mergeHistorySurgicalWithHistorySportList,
                              removeHistory: (history) {
                                setState(() {
                                  widget.removeHistory!(history);
                                });
                              },
                              addHistory: (history) {
                                setState(() {
                                  createAndAddHistory(history);
                                });
                              },
                              addSelectedHistories: () {
                                widget.addSelectedHistories!();
                              },
                              isServiceSelected: (master) => isServiceSelected(master),
                            ),
                          ),
                          NetworkBaseView(
                            baseViewModel: model,
                            child: MasterKeyCheckboxSearchWidget(
                              model: model,
                              masterList: model.historyMedicalList,
                              removeHistory: (history) {
                                setState(() {
                                  widget.removeHistory!(history);
                                });
                              },
                              addHistory: (history) {
                                setState(() {
                                  createAndAddHistory(history);
                                });
                              },
                              addSelectedHistories: () {
                                widget.addSelectedHistories!();
                              },
                              isServiceSelected: (master) => isServiceSelected(master),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    height: MediaQuery.of(context).size.height * 0.11,
                  )
                ],
              )),
            ),
            bottomSheet: model.state != ViewState.Idle
                ? Container(
                    height: 0,
                  )
                : CustomBottomSheetContainer(
                    label: TranslationBase.of(context).addSelectedHistories,
                    onTap: () {
                      widget.addSelectedHistories!();
                    },
                  ),
          ),
        ));
  }

  createAndAddHistory(MasterKeyModel history) {
    List<MySelectedHistory> myhistory = widget.myHistoryList!.where((element) => history.id == element.selectedHistory!.id && history.typeId == element.selectedHistory!.typeId).toList();

    if (myhistory.isEmpty) {
      setState(() {
        MySelectedHistory mySelectedHistory = SoapUtils.generateMySelectedHistory(remark: history.remarks ?? "", history: history, isChecked: true);

        widget.myHistoryList!.add(mySelectedHistory);
      });
    } else {
      myhistory.first.isChecked = true;
    }
  }

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