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/viewstate.dart';
import 'package:doctor_app_flutter/core/model/prescription_model.dart';
import 'package:doctor_app_flutter/core/viewModel/patient-ucaf-viewmodel.dart';
import 'package:doctor_app_flutter/models/SOAP/GetAssessmentResModel.dart';
import 'package:doctor_app_flutter/models/SOAP/master_key_model.dart';
import 'package:doctor_app_flutter/models/SOAP/order-procedure.dart';
import 'package:doctor_app_flutter/models/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/profile/UCAF/page-stepper-widget.dart';
import 'package:doctor_app_flutter/util/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/util/helpers.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:doctor_app_flutter/widgets/patients/profile/patient-profile-header-new-design-app-bar.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:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';

import '../../../../routes.dart';

class UcafDetailScreen extends StatefulWidget {
  @override
  _UcafDetailScreenState createState() => _UcafDetailScreenState();
}

class _UcafDetailScreenState extends State<UcafDetailScreen> {
  int _activeTap = 0;

  @override
  Widget build(BuildContext context) {
    final routeArgs = ModalRoute.of(context).settings.arguments as Map;
    PatiantInformtion patient = routeArgs['patient'];
    String patientType = routeArgs['patientType'];
    String arrivalType = routeArgs['arrivalType'];

    final screenSize = MediaQuery.of(context).size;

    return BaseView<UcafViewModel>(
        onModelReady: (model) async {
          model.resetDataInFirst();
          await model.getLanguage();
          await model.getPatientAssessment(patient);
        },
        builder: (_, model, w) => AppScaffold(
              baseViewModel: model,
              isShowAppBar: true,
              appBar: PatientProfileHeaderNewDesignAppBar(
                  patient, patientType, arrivalType),
              appBarTitle: TranslationBase.of(context).ucaf,
              body: Column(
                children: [
                  Expanded(
                    child: Container(
                      child: SingleChildScrollView(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // PatientHeaderWidgetNoAvatar(patient),
                            Container(
                              margin: EdgeInsets.all(16.0),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  AppText(
                                    "${TranslationBase.of(context).patient}",
                                    fontFamily: 'Poppins',
                                    fontSize: SizeConfig.textMultiplier * 1.6,
                                    fontWeight: FontWeight.w600,
                                  ),
                                  AppText(
                                    "${TranslationBase.of(context).ucaf}",
                                    fontFamily: 'Poppins',
                                    fontSize: SizeConfig.textMultiplier * 3,
                                    fontWeight: FontWeight.bold,
                                  )
                                ],
                              ),
                            ),
                            PageStepperWidget(
                              stepsCount: 2,
                              currentStepIndex: 2,
                              screenSize: screenSize,
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            Container(
                              margin: EdgeInsets.symmetric(
                                  vertical: 16, horizontal: 16),
                              child: Column(
                                children: [
                                  treatmentStepsBar(
                                      context, model, screenSize, patient),
                                  SizedBox(
                                    height: 16,
                                  ),
                                  ...getSelectedTreatmentStepItem(
                                      context, model),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                    child: Row(
                      children: [
                        Expanded(
                          child: Container(
                            child: AppButton(
                              title: TranslationBase.of(context).cancel,
                              hasBorder: true,
                              vPadding: 8,
                              hPadding: 8,
                              borderColor: Colors.white,
                              color: Colors.white,
                              fontColor: HexColor("#B8382B"),
                              fontSize: 2.2,
                              onPressed: () {
                                Navigator.of(context).popUntil((route) {
                                  return route.settings.name ==
                                      PATIENTS_PROFILE;
                                });
                              },
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 8,
                        ),
                        Expanded(
                          child: Container(
                            child: AppButton(
                              title: TranslationBase.of(context).save,
                              hasBorder: true,
                              vPadding: 8,
                              hPadding: 8,
                              borderColor: HexColor("#B8382B"),
                              color: HexColor("#B8382B"),
                              fontColor: Colors.white,
                              fontSize: 2.0,
                              onPressed: () async {
                                await model.postUCAF(patient);
                                if (model.state == ViewState.Idle) {
                                  DrAppToastMsg.showSuccesToast(
                                      TranslationBase.of(context)
                                          .postUcafSuccessMsg);
                                  Navigator.of(context).popUntil((route) {
                                    return route.settings.name ==
                                        PATIENTS_PROFILE;
                                  });
                                } else {
                                  DrAppToastMsg.showErrorToast(model.error);
                                }
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ));
  }

  Widget treatmentStepsBar(BuildContext _context, UcafViewModel model,
      Size screenSize, PatiantInformtion patient) {
    List<String> __treatmentSteps = [
      TranslationBase.of(context).diagnosis.toUpperCase(),
      TranslationBase.of(context).medications.toUpperCase(),
      TranslationBase.of(context).procedures.toUpperCase(),
    ];
    return Container(
      height: screenSize.height * 0.070,
      decoration: Helpers.containerBorderDecoration(
          Color(0Xffffffff), Color(0xFFCCCCCC)),
      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: Helpers.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: () async {
                print(__treatmentSteps.indexOf(item));
                if (__treatmentSteps.indexOf(item) == 0) {
                  await model.getPatientAssessment(patient);
                } else if (__treatmentSteps.indexOf(item) == 1) {
                  await model.getPrescription(patient);
                }
                if (__treatmentSteps.indexOf(item) == 2) {
                  await model.getOrderProcedures(patient);
                }
                setState(() {
                  _activeTap = __treatmentSteps.indexOf(item);
                });
              },
            ),
          );
        }).toList(),
      ),
    );
  }

  List<Widget> getSelectedTreatmentStepItem(
      BuildContext _context, UcafViewModel model) {
    switch (_activeTap) {
      case 0:
        if (model.patientAssessmentList != null) {
          return [
            ...List.generate(
                model.patientAssessmentList.length,
                (index) => DiagnosisWidget(
                    model, model.patientAssessmentList[index])).toList()
          ];
        } else {
          return [
            Container(),
          ];
        }
        break;
      case 1:
        return [
          ...List.generate(
              model.prescriptionList != null
                  ? model.prescriptionList.entityList.length
                  : 0,
              (index) => MedicationWidget(
                  model, model.prescriptionList.entityList[index])).toList()
        ];
        break;
      case 2:
        if (model.orderProcedures != null) {
          return [
            ...List.generate(
                    model.orderProcedures.length,
                    (index) =>
                        ProceduresWidget(model, model.orderProcedures[index]))
                .toList()
          ];
        } else {
          return [
            Container(),
          ];
        }
        break;
      default:
        return [
          Container(),
        ];
    }
  }
}

class DiagnosisWidget extends StatelessWidget {
  final UcafViewModel model;
  final GetAssessmentResModel diagnosis;

  DiagnosisWidget(this.model, this.diagnosis);

  @override
  Widget build(BuildContext context) {
    MasterKeyModel diagnosisType = model.findMasterDataById(
        masterKeys: MasterKeysService.DiagnosisType,
        id: diagnosis.diagnosisTypeID);
    MasterKeyModel diagnosisCondition = model.findMasterDataById(
        masterKeys: MasterKeysService.DiagnosisCondition,
        id: diagnosis.conditionID);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            AppText(
              "${TranslationBase.of(context).diagnoseType}: ",
              fontWeight: FontWeight.bold,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
            AppText(
              diagnosisType != null
                  ? model.selectedLanguage == 'ar'
                      ? diagnosisType.nameAr
                      : diagnosisType.nameEn
                  : "-",
              fontWeight: FontWeight.normal,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
          ],
        ),
        SizedBox(
          height: 4,
        ),
        Row(
          children: [
            Expanded(
              child: AppText(
                diagnosis.asciiDesc,
                fontWeight: FontWeight.bold,
                fontSize: SizeConfig.textMultiplier * 2.0,
              ),
            ),
          ],
        ),
        SizedBox(
          height: 4,
        ),
        Row(
          children: [
            AppText(
              "${TranslationBase.of(context).condition}: ",
              fontWeight: FontWeight.bold,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
            AppText(
              "${diagnosisCondition != null ? model.selectedLanguage == 'ar' ? diagnosisCondition.nameAr : diagnosisCondition.nameEn : "-"}",
              fontWeight: FontWeight.normal,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
          ],
        ),
        SizedBox(
          height: 4,
        ),
        Row(
          children: [
            AppText(
              "${TranslationBase.of(context).icd}: ",
              fontWeight: FontWeight.bold,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
            AppText(
              "${diagnosis.icdCode10ID}",
              fontWeight: FontWeight.normal,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
          ],
        ),
        SizedBox(
          height: 16,
        ),
        const Divider(
          color: Color(0xffCCCCCC),
          height: 1,
          thickness: 1,
          indent: 0,
          endIndent: 0,
        ),
        SizedBox(
          height: 16,
        ),
      ],
    );
  }
}

class MedicationWidget extends StatelessWidget {
  final UcafViewModel model;
  final EntityList prescription;

  MedicationWidget(this.model, this.prescription);

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            AppText(
              "${TranslationBase.of(context).id}: ",
              fontWeight: FontWeight.bold,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
            AppText(
              "${prescription.medicineCode}",
              fontWeight: FontWeight.normal,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
            SizedBox(
              width: 16,
            ),
            AppText(
              "${TranslationBase.of(context).price}: ",
              fontWeight: FontWeight.bold,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
            AppText(
              "${prescription.medicationPrice}",
              fontWeight: FontWeight.normal,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
            SizedBox(
              width: 16,
            ),
            AppText(
              "${TranslationBase.of(context).quantity}: ",
              fontWeight: FontWeight.bold,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
            AppText(
              "${prescription.quantity}",
              fontWeight: FontWeight.normal,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
          ],
        ),
        SizedBox(
          height: 4,
        ),
        Row(
          children: [
            AppText(
              "${TranslationBase.of(context).durDays}: ",
              fontWeight: FontWeight.bold,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
            AppText(
              "${prescription.doseDurationDays}",
              fontWeight: FontWeight.normal,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
          ],
        ),
        SizedBox(
          height: 4,
        ),
        Row(
          children: [
            Expanded(
              child: AppText(
                "${prescription.medicationName}",
                fontWeight: FontWeight.bold,
                fontSize: SizeConfig.textMultiplier * 2.0,
              ),
            ),
          ],
        ),
        SizedBox(
          height: 4,
        ),
        Row(
          children: [
            Expanded(
              child: AppText(
                "${prescription.doseDetail}",
                fontWeight: FontWeight.normal,
                fontSize: SizeConfig.textMultiplier * 2.0,
              ),
            ),
          ],
        ),
        SizedBox(
          height: 16,
        ),
        const Divider(
          color: Color(0xffCCCCCC),
          height: 1,
          thickness: 1,
          indent: 0,
          endIndent: 0,
        ),
        SizedBox(
          height: 16,
        ),
      ],
    );
  }
}

class ProceduresWidget extends StatelessWidget {
  final UcafViewModel model;
  final OrderProcedure procedure;

  ProceduresWidget(this.model, this.procedure);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          children: [
            AppText(
              "${TranslationBase.of(context).codeNo}: ",
              fontWeight: FontWeight.bold,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
            AppText(
              procedure.achiCode,
              fontWeight: FontWeight.normal,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  AppText(
                    "${TranslationBase.of(context).quantity}: ",
                    fontWeight: FontWeight.bold,
                    fontSize: SizeConfig.textMultiplier * 2.0,
                  ),
                  AppText(
                    "${procedure.lineItemNo}",
                    fontWeight: FontWeight.normal,
                    fontSize: SizeConfig.textMultiplier * 2.0,
                  ),
                ],
              ),
            ),
          ],
        ),
        SizedBox(
          height: 4,
        ),
        Row(
          children: [
            Expanded(
              child: AppText(
                procedure.procedureName,
                fontWeight: FontWeight.bold,
                fontSize: SizeConfig.textMultiplier * 2.0,
              ),
            ),
          ],
        ),
        SizedBox(
          height: 4,
        ),
        Row(
          children: [
            AppText(
              "${TranslationBase.of(context).covered}: ",
              fontWeight: FontWeight.bold,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
            AppText(
              "${procedure.isCovered}",
              fontWeight: FontWeight.normal,
              color: procedure.isCovered ? Colors.green : Colors.red,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
            SizedBox(
              width: 16,
            ),
            AppText(
              "${TranslationBase.of(context).approvalRequired}: ",
              fontWeight: FontWeight.bold,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
            AppText(
              "${procedure.isApprovalRequired}",
              fontWeight: FontWeight.normal,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
          ],
        ),
        SizedBox(
          height: 4,
        ),
        Row(
          children: [
            AppText(
              "${TranslationBase.of(context).uncoveredByDoctor}: ",
              fontWeight: FontWeight.bold,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
            AppText(
              "${procedure.isUncoveredByDoctor}",
              fontWeight: FontWeight.normal,
              fontSize: SizeConfig.textMultiplier * 2.0,
            ),
          ],
        ),
        SizedBox(
          height: 16,
        ),
        const Divider(
          color: Color(0xffCCCCCC),
          height: 1,
          thickness: 1,
          indent: 0,
          endIndent: 0,
        ),
        SizedBox(
          height: 16,
        ),
      ],
    );
  }
}
