import 'package:doctor_app_flutter/config/size_config.dart';
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/model/SOAP/master_key_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/selected_items/my_selected_assement.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/viewModel/SOAP_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/assessment/assessment_call_back.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/shared_soap_widgets/SOAP_open_items.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/shared_soap_widgets/SOAP_step_header.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/shared_soap_widgets/expandable_SOAP_widget.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/shared_soap_widgets/remark_text.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/soap_utils.dart';
import 'package:doctor_app_flutter/utils/date-utils.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/utils/utils.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../soap_update/assessment/add_assessment_details.dart';

import 'widget/current_diagnosis.dart';
import 'widget/previous_diagnosis.dart';

// ignore: must_be_immutable
class UpdateAssessmentPage extends StatefulWidget {
  final Function changePageViewIndex;
  final PatiantInformtion patientInfo;
  final Function changeLoadingState;
  final int currentIndex;

  UpdateAssessmentPage(
      {Key? key,
      required this.changePageViewIndex,
      required this.patientInfo,
      required this.changeLoadingState,
      required this.currentIndex});

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

class _UpdateAssessmentPageState extends State<UpdateAssessmentPage>
    with SingleTickerProviderStateMixin
    implements AssessmentCallBack {
  bool isAssessmentExpand = false;
  List<MySelectedAssessment> mySelectedAssessmentList = [];
  bool isPrescriptionOrder = false;
  TabController? _tabController;

  @override
  void initState() {
    _tabController = new TabController(length: 2, vsync: this);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);

    return BaseView<SOAPViewModel>(
      onModelReady: (model) async {
        model.setAssessmentCallBack(this);
        mySelectedAssessmentList.clear();
        WidgetsBinding.instance.addPostFrameCallback((_) async {
          widget.changeLoadingState(true);
          model.getConditionAndType(widget.patientInfo);
          model.getPreviousPatientDetails(widget.patientInfo);
          model.getCurrentDiagnosisList(widget.patientInfo);
          widget.changeLoadingState(false);
          //todo handle get diagnosis list
        });
      },
      builder: (_, model, w) => AppScaffold(
        isShowAppBar: false,
        isLoading: model.state == ViewState.BusyLocal,
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        body: SingleChildScrollView(
          physics: ScrollPhysics(),
          child: Container(
            color: Theme.of(context).scaffoldBackgroundColor,
            child: Center(
              child: FractionallySizedBox(
                widthFactor: 0.9,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    SOAPStepHeader(
                      currentIndex: widget.currentIndex,
                      changePageViewIndex: widget.changePageViewIndex,
                      patientInfo: widget.patientInfo,
                    ),
                    ExpandableSOAPWidget(
                      headerTitle: TranslationBase.of(context).assessment,
                      onTap: () {
                        setState(() {
                          isAssessmentExpand = !isAssessmentExpand;
                        });
                      },
                      child: Column(children: [
                        SizedBox(
                          height: 10,
                        ),

                        SizedBox(
                          height: 64,
                          child: TabBar(
                            indicatorColor: Color(0xFFD02127),
                            unselectedLabelColor: Color(0xFF6D6D6D),
                            labelColor: Color(0xFF2B353E),
                            tabs: [
                              Tab(
                                child: Text(
                                  TranslationBase.of(context)
                                      .currentDiagnosis,
                                  style: TextStyle(
                                  color: Color(0xFF6D6D6D),
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  letterSpacing: -0.56,)
                                ),
                              ),
                              Tab(
                                child:  Text(
                                    TranslationBase.of(context)
                                        .previousDiagnosis,
                                    style: TextStyle(
                                      color: Color(0xFF6D6D6D),
                                      fontSize: 14,
                                      fontWeight: FontWeight.w600,
                                      letterSpacing: -0.56,)
                                )
                              )
                            ],
                            controller: _tabController,
                          ),
                        ),
                        SizedBox(
                          height: 300,
                          child: TabBarView(
                            controller: _tabController,
                            children: [
                              CurrentDiagnosis(
                                patientInfo: widget.patientInfo,
                                model: model,
                                currentDiagnosisItems: model.diagnosisList,
                              ),
                              PreviousDiagnosis(
                                diagnosisItems: model.patientPreviousDiagnosis,
                                patientInfo: widget.patientInfo,
                              )
                            ],
                          ),
                        )
                      ]),
                      isExpanded: isAssessmentExpand,
                    ),
                    SizedBox(
                      height: 130,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  openAssessmentDialog(BuildContext context,
      {MySelectedAssessment? assessment,
      bool isUpdate = false,
      required SOAPViewModel model}) {
    if (assessment == null) {
      assessment = SoapUtils.generateMySelectedAssessment(
          remark: '', appointmentNo: widget.patientInfo.appointmentNo);
    }
    showModalBottomSheet(
        backgroundColor: Colors.white,
        isScrollControlled: true,
        context: context,
        builder: (context) {
          return AddAssessmentDetails(
              mySelectedAssessment: assessment!,
              patientInfo: widget.patientInfo,
              isUpdate: isUpdate,
              mySelectedAssessmentList: mySelectedAssessmentList,
              addSelectedAssessment: (MySelectedAssessment mySelectedAssessment,
                  bool isUpdate) async {
                setState(() {
                  if (!isUpdate)
                    mySelectedAssessmentList.add(mySelectedAssessment);
                });
              });
        });
  }

  @override
  nextFunction(model) {
    if (mySelectedAssessmentList.isEmpty) {
      Utils.showErrorToast(TranslationBase.of(context).assessmentErrorMsg);
    } else if (!checkPrimaryDiagnosis()) {
      Utils.showErrorToast(TranslationBase.of(context).onePrimaryDiagnosis);
    } else {
      widget.changeLoadingState(true);
      widget.changePageViewIndex(3);
    }
  }

  bool checkPrimaryDiagnosis() {
    ProjectViewModel projectViewModel =
        Provider.of<ProjectViewModel>(context, listen: false);
    bool isVidaPlus = Utils.isVidaPlusProject(
        projectViewModel, widget.patientInfo.projectId!);
    List<MySelectedAssessment> type = mySelectedAssessmentList
        .where((element) =>
            (element.selectedDiagnosisType!.id == 2 && isVidaPlus == false) ||
            (element.selectedDiagnosisType!.code == '3' && isVidaPlus == true))
        .toList();
    return type.isEmpty ? false : true;
  }
}
