import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/core/model/note/note_model.dart';
import 'package:doctor_app_flutter/core/model/note/update_note_model.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/model/patient/progress_note_request.dart';
import 'package:doctor_app_flutter/core/service/AnalyticsService.dart';
import 'package:doctor_app_flutter/core/viewModel/authentication_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/patient_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/locator.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/profile/notes/note/update_note.dart';
import 'package:doctor_app_flutter/utils/date-utils.dart';
import 'package:doctor_app_flutter/utils/dr_app_shared_pref.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/widgets/patients/profile/add-order/addNewOrder.dart';
import 'package:doctor_app_flutter/widgets/patients/profile/app_bar/patient-profile-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/card_with_bg_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/divider_with_spaces_around.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:provider/provider.dart';

DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();

class ProgressNoteScreen extends StatefulWidget {
  final int visitType;


  const ProgressNoteScreen({Key? key, required this.visitType}) : super(key: key);

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

class _ProgressNoteState extends State<ProgressNoteScreen> {
  List<NoteModel> notesList = [];
  var filteredNotesList;
  bool isDischargedPatient = false;
  late AuthenticationViewModel authenticationViewModel;
  late ProjectViewModel projectViewModel;
  bool isVidaPlusProject = false;

  getProgressNoteList(BuildContext context, PatientViewModel model, {bool isLocalBusy = false}) async {
    final routeArgs = ModalRoute.of(context)!.settings.arguments as Map;
    PatiantInformtion patient = routeArgs['patient'];
    String? token = await sharedPref.getString(TOKEN);
    String? type = await sharedPref.getString(SLECTED_PATIENT_TYPE);

    print(type);
    ProgressNoteRequest progressNoteRequest = ProgressNoteRequest(
        visitType: widget.visitType,
        // if equal 5 then this will return progress note
        admissionNo: (isVidaPlusProject)?patient.admissionID:int.parse(patient.admissionNo!),
        projectID: patient.projectId,
        tokenID: token,
        patientTypeID: patient.patientType,
        languageID: 2);
    model.getPatientProgressNote(progressNoteRequest.toJson(),patient, isLocalBusy: isLocalBusy, isVidaPlus: isVidaPlusProject).then((c) {
      notesList = model.patientProgressNoteList;
    });
  }

  @override
  Widget build(BuildContext context) {
    authenticationViewModel = Provider.of(context);
    projectViewModel = Provider.of(context);
    final routeArgs = ModalRoute.of(context)!.settings.arguments as Map;
    PatiantInformtion patient = routeArgs['patient'];
    String arrivalType = routeArgs['arrivalType'];
    isVidaPlusProject = routeArgs['isVidaPlusProject'] ?? false;
    if (routeArgs.containsKey('isDischargedPatient')) isDischargedPatient = routeArgs['isDischargedPatient'];
    return BaseView<PatientViewModel>(
      onModelReady: (model) => getProgressNoteList(context, model, ),
      builder: (_, model, w) => AppScaffold(
        baseViewModel: model,
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        // appBarTitle: TranslationBase.of(context).progressNote,
        appBar: PatientProfileAppBar(
          patient,
          isInpatient: true,
        ),
        body: Container(
          color: Colors.grey[200],
          child: Column(
            children: <Widget>[
              if (!isDischargedPatient)
                AddNewOrder(
                  onTap: () async {
                    await locator<AnalyticsService>().logEvent(
                      eventCategory: "Progress Note Screen",
                      eventAction: "Update Progress Note",
                    );
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => UpdateNoteOrder(
                          patientModel: model,
                          patient: patient,
                          visitType: widget.visitType,
                          isUpdate: false,
                          isVidaPlusProject:isVidaPlusProject
                        ),
                        settings: RouteSettings(name: 'UpdateNoteOrder'),
                      ),
                    );
                  },
                  label: widget.visitType == 3 ? TranslationBase.of(context).addNewOrderSheet : TranslationBase.of(context).addProgressNote,
                ),
              Expanded(
                child: Container(
                  child: ListView.builder(
                      itemCount: model.patientProgressNoteList.length,
                      itemBuilder: (BuildContext ctxt, int index) {
                        return FractionallySizedBox(
                          widthFactor: 0.95,
                          child: CardWithBgWidget(
                            hasBorder: false,
                            bgColor: model.patientProgressNoteList[index].status == 1 && authenticationViewModel.doctorProfile!.doctorID != model.patientProgressNoteList[index].createdBy
                                ? Color(0xFFCC9B14)
                                : model.patientProgressNoteList[index].status == 4
                                    ? Colors.red.shade700
                                    : model.patientProgressNoteList[index].status == 2
                                        ? AppGlobal.appGreenColor
                                        : Color(0xFFCC9B14),
                            widget: Column(
                              children: [
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    if (model.patientProgressNoteList[index].status == 1 && authenticationViewModel.doctorProfile!.doctorID != model.patientProgressNoteList[index].createdBy)
                                      AppText(
                                        TranslationBase.of(context).notePending,
                                        fontWeight: FontWeight.bold,
                                        color: Color(0xFFCC9B14),
                                        fontSize: 12,
                                      ),
                                    if (model.patientProgressNoteList[index].status == 4)
                                      AppText(
                                        TranslationBase.of(context).noteCanceled,
                                        fontWeight: FontWeight.bold,
                                        color: Colors.red.shade700,
                                        fontSize: 12,
                                      ),
                                    if (model.patientProgressNoteList[index].status == 2)
                                      AppText(
                                        TranslationBase.of(context).noteVerified,
                                        fontWeight: FontWeight.bold,
                                        color: AppGlobal.appGreenColor,
                                        fontSize: 12,
                                      ),
                                    if (model.patientProgressNoteList[index].status != 2 &&
                                        model.patientProgressNoteList[index].status != 4 &&
                                        authenticationViewModel.doctorProfile!.doctorID == model.patientProgressNoteList[index].createdBy)
                                      Row(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          InkWell(
                                            onTap: () {
                                              Navigator.push(
                                                context,
                                                MaterialPageRoute(
                                                    builder: (context) => UpdateNoteOrder(
                                                          note: model.patientProgressNoteList[index],
                                                          patientModel: model,
                                                          patient: patient,
                                                          visitType: widget.visitType,
                                                          isUpdate: true,
                                                        )),
                                              );
                                            },
                                            child: Container(
                                              decoration: BoxDecoration(
                                                color: Colors.grey[600],
                                                borderRadius: BorderRadius.circular(10),
                                              ),
                                              // color:Colors.red[600],

                                              child: Row(
                                                children: [
                                                  Icon(
                                                    DoctorApp.edit_1,
                                                    size: 12,
                                                    color: Colors.white,
                                                  ),
                                                  SizedBox(
                                                    width: 2,
                                                  ),
                                                  AppText(
                                                    TranslationBase.of(context).update,
                                                    fontSize: 10,
                                                    color: Colors.white,
                                                  ),
                                                ],
                                              ),
                                              padding: EdgeInsets.all(6),
                                            ),
                                          ),
                                          SizedBox(
                                            width: 10,
                                          ),
                                          InkWell(
                                            onTap: () async {
                                              showMyDialog(
                                                  context: context,
                                                  actionName: "verify",
                                                  confirmFun: () async {
                                                    GifLoaderDialogUtils.showMyDialog(context);
                                                    UpdateNoteReqModel reqModel = UpdateNoteReqModel(
                                                      admissionNo: int.parse(patient.admissionNo!),
                                                      cancelledNote: false,
                                                      lineItemNo: model.patientProgressNoteList[index].lineItemNo,
                                                      conditionId: model.patientProgressNoteList[index].condition,
                                                      createdBy: model.patientProgressNoteList[index].createdBy,
                                                      notes: model.patientProgressNoteList[index].notes,
                                                      verifiedNote: true,
                                                      patientTypeID: patient.patientType,
                                                      patientOutSA: false,
                                                    );
                                                    await model.updatePatientProgressNote(reqModel);
                                                    await getProgressNoteList(context, model, isLocalBusy: true,);
                                                    GifLoaderDialogUtils.hideDialog(context);
                                                  });
                                            },
                                            child: Container(
                                              decoration: BoxDecoration(
                                                color: AppGlobal.appGreenColor,
                                                borderRadius: BorderRadius.circular(10),
                                              ),
                                              // color:Colors.red[600],

                                              child: Row(
                                                children: [
                                                  Icon(
                                                    FontAwesomeIcons.check.data,
                                                    size: 12,
                                                    color: Colors.white,
                                                  ),
                                                  SizedBox(
                                                    width: 2,
                                                  ),
                                                  AppText(
                                                    TranslationBase.of(context).noteVerify,
                                                    fontSize: 10,
                                                    color: Colors.white,
                                                  ),
                                                ],
                                              ),
                                              padding: EdgeInsets.all(6),
                                            ),
                                          ),
                                          SizedBox(
                                            width: 10,
                                          ),
                                          InkWell(
                                            onTap: () async {
                                              showMyDialog(
                                                  context: context,
                                                  actionName: TranslationBase.of(context).cancel,
                                                  confirmFun: () async {
                                                    GifLoaderDialogUtils.showMyDialog(
                                                      context,
                                                    );
                                                    UpdateNoteReqModel reqModel = UpdateNoteReqModel(
                                                      admissionNo: int.parse(patient.admissionNo!),
                                                      conditionId: model.patientProgressNoteList[index].condition,
                                                      cancelledNote: true,
                                                      lineItemNo: model.patientProgressNoteList[index].lineItemNo,
                                                      createdBy: model.patientProgressNoteList[index].createdBy,
                                                      notes: model.patientProgressNoteList[index].notes,
                                                      verifiedNote: false,
                                                      patientTypeID: patient.patientType,
                                                      patientOutSA: false,
                                                    );
                                                    await model.updatePatientProgressNote(reqModel);
                                                    await getProgressNoteList(context, model, isLocalBusy: true, );
                                                    GifLoaderDialogUtils.hideDialog(context);
                                                  });
                                            },
                                            child: Container(
                                              decoration: BoxDecoration(
                                                color: Colors.red[600],
                                                borderRadius: BorderRadius.circular(10),
                                              ),
                                              // color:Colors.red[600],

                                               child: Row(
                                                 children: [
                                                   Icon(
                                                     FontAwesomeIcons.trash.data,
                                                     size: 12,
                                                     color: Colors.white,
                                                   ),
                                                  SizedBox(
                                                    width: 2,
                                                  ),
                                                  AppText(
                                                    'Cancel',
                                                    fontSize: 10,
                                                    color: Colors.white,
                                                  ),
                                                ],
                                              ),
                                              padding: EdgeInsets.all(6),
                                            ),
                                          ),
                                          SizedBox(
                                            width: 10,
                                          )
                                        ],
                                      ),
                                    SizedBox(
                                      height: 10,
                                    ),
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Container(
                                          width: MediaQuery.of(context).size.width * 0.60,
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Row(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: [
                                                  AppText(
                                                    TranslationBase.of(context).createdBy + ' ',
                                                    fontSize: 10,
                                                  ),
                                                  Expanded(
                                                    child: AppText(
                                                      model.patientProgressNoteList[index].doctorName ?? '',
                                                      fontWeight: FontWeight.w600,
                                                      fontSize: 12,
                                                      isCopyable: true,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                              Row(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: [
                                                  AppText(
                                                    TranslationBase.of(context).conditionDescription + ' : ',
                                                    fontSize: 10,
                                                  ),
                                                  Expanded(
                                                    child: AppText(
                                                      model.patientProgressNoteList[index].conditionDescription ?? '',
                                                      fontWeight: FontWeight.w600,
                                                      fontSize: 12,
                                                      isCopyable: true,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ],
                                          ),
                                        ),
                                        Column(
                                          children: [
                                            AppText(
                                              model.patientProgressNoteList[index].createdOn != null
                                                  ? AppDateUtils.getDayMonthYearDateFormatted(AppDateUtils.getDateTimeFromServerFormat(model.patientProgressNoteList[index].createdOn!),
                                                      isArabic: projectViewModel.isArabic, isMonthShort: true)
                                                  : AppDateUtils.getDayMonthYearDateFormatted(DateTime.now(), isArabic: projectViewModel.isArabic),
                                              fontWeight: FontWeight.w600,
                                              fontSize: 14,
                                              isCopyable: true,
                                            ),
                                            AppText(
                                              model.patientProgressNoteList[index].createdOn != null
                                                  ? AppDateUtils.getHour(AppDateUtils.getDateTimeFromServerFormat(model.patientProgressNoteList[index].createdOn!))
                                                  : AppDateUtils.getHour(DateTime.now()),
                                              fontWeight: FontWeight.w600,
                                              fontSize: 14,
                                              isCopyable: true,
                                            ),
                                          ],
                                          crossAxisAlignment: CrossAxisAlignment.end,
                                        )
                                      ],
                                    ),
                                    SizedBox(
                                      height: 8,
                                    ),
                                    Row(mainAxisAlignment: MainAxisAlignment.start, children: [
                                      Expanded(
                                        child: AppText(
                                          model.patientProgressNoteList[index].notes!,
                                          fontSize: 10,
                                          isCopyable: true,
                                        ),
                                      ),
                                    ])
                                  ],
                                ),
                                SizedBox(
                                  height: 20,
                                ),
                              ],
                            ),
                          ),
                        );
                      }),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// TODO  Elham* Make this as custom Dialog
  showMyDialog({required BuildContext context, required Function confirmFun, required String actionName}) {
    showDialog(
        context: context,
        builder: (ctx) => Center(
              child: Container(
                width: MediaQuery.of(context).size.width * 0.8,
                height: 200,
                child: AppScaffold(
                  isShowAppBar: false,
                  body: Container(
                    color: Colors.white,
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          // SizedBox(height: 20,),
                          SizedBox(
                            height: 10,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              AppText(
                                TranslationBase.of(context).noteConfirm,
                                fontWeight: FontWeight.w600,
                                color: Colors.black,
                                fontSize: 16,
                              ),
                            ],
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          DividerWithSpacesAround(),
                          SizedBox(
                            height: 12,
                          ),

                          Container(
                            padding: EdgeInsets.all(20),
                            color: Colors.white,
                            child: AppText(
                              projectViewModel.isArabic ? "هل أنت متأكد أنك تريد تنفيذ $actionName  هذا الأمر؟" : 'Are you sure you want $actionName this order?',
                              fontSize: 15,
                              textAlign: TextAlign.center,
                            ),
                          ),

                          SizedBox(
                            height: 8,
                          ),
                          DividerWithSpacesAround(),
                          FractionallySizedBox(
                            widthFactor: 0.75,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                ElevatedButton(
                                    child: AppText(
                                      TranslationBase.of(context).cancel,
                                      fontWeight: FontWeight.w600,
                                      color: Colors.black,
                                      fontSize: 16,
                                    ), //Text("Cancel"),
                                    onPressed: () {
                                      Navigator.of(context).pop();
                                    }),
                                ElevatedButton(
                                    child: AppText(
                                      TranslationBase.of(context).noteConfirm,
                                      fontWeight: FontWeight.w600,
                                      color: Colors.red.shade700,
                                      fontSize: 16,
                                    ), //Text("Confirm", ),
                                    onPressed: () async {
                                      await confirmFun();
                                      Navigator.of(context).pop();
                                    })
                              ],
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ));
  }
}
