import 'dart:ui';

import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/model/pharmacy-intervention-model/intervention_history.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/screens/pharmacy_intervention/widgets/InterventionCardItem.dart';
import 'package:doctor_app_flutter/screens/pharmacy_intervention/widgets/InterventionHistoryBottomSheet.dart';
import 'package:doctor_app_flutter/screens/pharmacy_intervention/widgets/NoInveterventionFound.dart';
import 'package:doctor_app_flutter/screens/pharmacy_intervention/widgets/PharmacyInterventionDialog.dart';
import 'package:doctor_app_flutter/utils/dr_app_toast_msg.dart';
import 'viewmodel/pharmacy_intervention_view_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/patient_search/patient_search_header.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:flutter/material.dart';

class PharmacyIntervention extends StatefulWidget {
  @override
  State<PharmacyIntervention> createState() => _PharmacyInterventionState();
}

class _PharmacyInterventionState extends State<PharmacyIntervention> {
  bool isBottomSheetShown = false;
  @override
  Widget build(BuildContext context) {
    return BaseView<PharmacyInterventionViewModel>(onModelReady: (model) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Future.wait([
          model.getNursingStations(),
          model.getPharmacyIntervention(),
        ]);
      });
    }, builder: (_, model, __) {
      if (model.interventionHistoryList != null && !model.isBottomSheetShown) {
        model.toggleBottomOpenValue(true);
        WidgetsBinding.instance.addPostFrameCallback((_) {
          showBottomSheet(
            context,
            model,
            model.interventionHistoryList!.history!,
          );
        });
      }
      return AppScaffold(
        isShowAppBar: true,
        isLoading: model.state == ViewState.BusyLocal,
        appBar: PatientSearchHeader(
          title: TranslationBase.of(context).pharmacyApproval,
          fontSize: 18,
          showSearchIcon: true,
          onSearchPressed: () {
            SearchDialog(context, model);
          },
        ),
        appBarTitle: TranslationBase.of(context).pharmacyApproval,
        body: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            if (model.medicationList == null || model.medicationList?.medication?.isEmpty == true) ...{
              Expanded(
                child:
                NoInterventionFound()
                ,
              )
            } else ...{
              Expanded(
                  child: ListView.builder(
                      itemCount: model.medicationList?.medication?.length ?? 0,
                      itemBuilder: (context, index) => InterventionCardItem(
                            medication:
                                model.medicationList!.medication![index],
                            model: model,
                          )))
            }
          ],
        ),
      );
    });
  }

  final _sheet = GlobalKey();

  final _controller = DraggableScrollableController();

  @override
  void initState() {
    super.initState();
    _controller.addListener(_onChanged);
  }

  void _onChanged() {
    final currentSize = _controller.size;
    if (currentSize <= 0.05) _collapse();
  }

  void _collapse() => _animateSheet(sheet.snapSizes!.first);

  void _animateSheet(double size) {
    _controller.animateTo(
      size,
      duration: const Duration(milliseconds: 50),
      curve: Curves.easeInOut,
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  DraggableScrollableSheet get sheet =>
      (_sheet.currentWidget as DraggableScrollableSheet);

  void showBottomSheet(
    BuildContext context,
    PharmacyInterventionViewModel model,
    List<InterventionHistory> interventionHistory,
  ) {
    showModalBottomSheet(
      isDismissible: true,
      context: context,
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20), topRight: Radius.circular(20))),
      builder: (_) {
        return Padding(
          padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
          child: InterventionHistoryBottomSheet(
            interventionList: interventionHistory,
            model: model,
          ),
        );
      },
    ).then((value) {
      model.toggleShowBottomSheetValue();
      model.toggleBottomOpenValue(false);
    });
  }

  void SearchDialog(BuildContext context, PharmacyInterventionViewModel model) {
    showDialog(
        context: context,
        barrierDismissible: true, // user must tap button!
        builder: (_) {
          return PharmacyInterventionDialog(
              dateFrom: model.fromDate,
              dateTo: model.toDate,
              admissionNumber: model.admissionId,
              nursingStation: model.entity,
              patientID: model.patientID,
              station: model.nursingStations,
              onDispose: (dateFrom, dateTo, admissionNumber, patientId,
                  nursingStation) {
                if (dateFrom == model.fromDate &&
                    dateTo == model.toDate &&
                    admissionNumber == model.admissionId &&
                    patientId == model.patientID &&
                    nursingStation == model.nursingStationId) {
                  Navigator.of(context).pop();
                  return;
                }
                if (dateFrom.isEmpty && dateTo.isNotEmpty) {
                  DrAppToastMsg.showErrorToast(
                      TranslationBase.of(context).dateFromCanNotBeEmpty);
                  return;
                }
                if (dateFrom.isNotEmpty && dateTo.isEmpty) {
                  DrAppToastMsg.showErrorToast(
                      TranslationBase.of(context).dateToCanNotBeEmpty);
                  return;
                }
                model.getPharmacyIntervention(
                    admissionId: admissionNumber,
                    patientID: patientId,
                    nursingStationId:
                        "${nursingStation?.nursingStationID ?? '0'}",
                    toDate: dateTo,
                    fromDate: dateFrom,
                entity: nursingStation);
                Navigator.of(context).pop();
              });
        });
  }
}
