import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/viewModel/patient-ucaf-viewmodel.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/routes.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/profile/UCAF/widgets/diagnosis_widget.dart';
import 'package:doctor_app_flutter/screens/patients/profile/UCAF/widgets/medication_widget.dart';
import 'package:doctor_app_flutter/screens/patients/profile/UCAF/widgets/pocedures_widget.dart';
import 'package:doctor_app_flutter/utils/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/utils/tab_utils.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/errors/error_message.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class UcafDetailScreen extends StatefulWidget {
  final PatiantInformtion patient;
  final UcafViewModel model;
  final Function? changeLoadingState;

  UcafDetailScreen(this.patient, this.model, {this.changeLoadingState});

  @override
  _UcafDetailScreenState createState() => _UcafDetailScreenState(this.patient, this.model);
}

class _UcafDetailScreenState extends State<UcafDetailScreen> {
  final PatiantInformtion patient;
  final UcafViewModel model;

  UcafViewModel ucafModel = UcafViewModel();

  int _activeTap = 0;

  _UcafDetailScreenState(this.patient, this.model);

  @override
  void initState() {
    model.saveUCAFOnTap = () async {
      widget.changeLoadingState!(true);
      await ucafModel.postUCAF(patient);
      widget.changeLoadingState!(false);
      if (ucafModel.state == ViewState.Idle) {
        DrAppToastMsg.showSuccesToast(TranslationBase.of(context).postUcafSuccessMsg);
        Navigator.of(context).popUntil((route) {
          return route.settings.name == PATIENTS_PROFILE;
        });
      } else {
        DrAppToastMsg.showErrorToast(ucafModel.error);
      }
    };
    super.initState();
  }

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

    return BaseView<UcafViewModel>(
        onModelReady: (model) async {
          ucafModel = model;
          model.resetDataInFirst(firstPage: false);
          await model.getLanguage();
          await model.getPatientAssessment(patient);
          widget.changeLoadingState!(false);
        },
        builder: (_, model, w) => AppScaffold(
              baseViewModel: model,
              isShowAppBar: false,
              body: Column(
                children: [
                  Expanded(
                    child: Container(
                      child: SingleChildScrollView(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            treatmentStepsBar(context, model, screenSize, patient),
                            Container(
                              margin: EdgeInsets.symmetric(vertical: 16, horizontal: 16),
                              child: Column(
                                children: [
                                  SizedBox(
                                    height: 16,
                                  ),
                                  ...getSelectedTreatmentStepItem(context, model),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ));
  }

  Widget treatmentStepsBar(BuildContext _context, UcafViewModel model, Size screenSize, PatiantInformtion patient) {
    ProjectViewModel projectViewModel = Provider.of(context);
    List<String> __treatmentSteps = [
      TranslationBase.of(context).diagnosis,
      TranslationBase.of(context).medications,
      TranslationBase.of(context).procedures,
    ];
    return Container(
      height: TabUtils.getTabHeight(context),
      decoration: TabUtils.getBoxTabsBoxDecoration(projectViewModel: projectViewModel),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: __treatmentSteps.map((item) {
          bool _isActive = __treatmentSteps[_activeTap] == item ? true : false;
          return Expanded(
            child: InkWell(
              child: Center(
                child: Container(
                    height: screenSize.height * 0.070,
                    decoration: TabUtils.getBoxTabsBoxDecoration(
                        projectViewModel: projectViewModel,
                        isActive: _isActive,
                        isFirst: __treatmentSteps.indexOf(item) == 0,
                        isLast: __treatmentSteps.indexOf(item) == 2,
                        isMiddle: __treatmentSteps.indexOf(item) == 1),
                    child: Center(child: TabUtils.getTabText(title: item, isActive: _isActive))),
              ),
              onTap: () async {
                print(__treatmentSteps.indexOf(item));
                if (__treatmentSteps.indexOf(item) == 0) {
                  widget.changeLoadingState!(true);
                  await model.getPatientAssessment(patient);
                  widget.changeLoadingState!(false);
                } else if (__treatmentSteps.indexOf(item) == 1) {
                  widget.changeLoadingState!(true);
                  await model.getPrescription(patient);
                  widget.changeLoadingState!(false);
                }
                if (__treatmentSteps.indexOf(item) == 2) {
                  widget.changeLoadingState!(true);
                  await model.getOrderProcedures(patient);
                  widget.changeLoadingState!(false);
                }
                setState(() {
                  _activeTap = __treatmentSteps.indexOf(item);
                });
              },
            ),
          );
        }).toList(),
      ),
    );
  }

  List<Widget> getSelectedTreatmentStepItem(BuildContext _context, UcafViewModel model) {
    switch (_activeTap) {
      case 0:
        if (model.patientAssessmentList != null) {
          return [
            ListView.builder(
                itemCount: model.patientAssessmentList.length,
                scrollDirection: Axis.vertical,
                physics: ScrollPhysics(),
                shrinkWrap: true,
                itemBuilder: (context, index) {
                  return DiagnosisWidget(model, model.patientAssessmentList[index]);
                })
          ];
        } else {
          return [
            ErrorMessage(error: TranslationBase.of(context).noItem),
          ];
        }
        break;
      case 1:
        if (model.prescriptionList != null && model.prescriptionList!.entityList != null && model.prescriptionList!.entityList!.isNotEmpty) {
          return [
            ListView.builder(
                itemCount: model.prescriptionList != null ? model.prescriptionList!.entityList!.length : 0,
                scrollDirection: Axis.vertical,
                physics: ScrollPhysics(),
                shrinkWrap: true,
                itemBuilder: (context, index) {
                  return MedicationWidget(model, model.prescriptionList!.entityList![index]);
                })
          ];
        } else {
          return [
            ErrorMessage(error: TranslationBase.of(context).noItem),
          ];
        }
        break;
      case 2:
        if (model.orderProcedures != null && model.orderProcedures!.isNotEmpty) {
          return [
            ListView.builder(
                itemCount: model.orderProcedures!.length,
                scrollDirection: Axis.vertical,
                physics: ScrollPhysics(),
                shrinkWrap: true,
                itemBuilder: (context, index) {
                  return ProceduresWidget(model, model.orderProcedures![index]);
                })
          ];
        } else {
          return [
            ErrorMessage(error: TranslationBase.of(context).noItem),
          ];
        }
        break;
      default:
        return [
          Container(),
        ];
    }
  }
}
