/*!
 *
 * Copyright (c) 2021-2025 Diality Inc. - All Rights Reserved.
 * \copyright
 * THIS CODE MAY NOT BE COPIED OR REPRODUCED IN ANY FORM, IN PART OR IN
 * WHOLE, WITHOUT THE EXPLICIT PERMISSION OF THE COPYRIGHT OWNER.
 *
 * \file    PreTreatmentCreateContent.qml
 * \author  (last)      Nico Ramirez
 * \date    (last)      21-Aug-2025
 * \author  (original)  Nico Ramirez
 * \date    (original)  21-Aug-2025
 *
 */

// Qt
import QtQuick 2.15
import QtQuick.Controls 2.15

//  Qml
import "qrc:/globals"
import "qrc:/components"
import "qrc:/compounds"
import "qrc:/dialogs"
import "qrc:/pages/pretreatment"

Item { id: _root
    readonly property bool isValidated  : vTreatmentCreate.parametersValidated
    readonly property string editRx     : qsTr( "Edit Rx"    )
    readonly property string selectRx   : qsTr( "Select Rx"  )
    readonly property string clearAll   : qsTr( "Clear All"  )
    property int    currentIndex        : PreTreatmentCreateContent.PatientPrescription
    property bool editingEnabled        : true

    onIsValidatedChanged : canEdit ( ! isValidated )

    onCurrentIndexChanged: _prescriptionMenu.index = _root.currentIndex

    enum Page {
        PatientPrescription     ,
        TreatmentSettings       ,
        Count
    }

    function canEdit  (state) { editingEnabled = state && ! vTDOpMode.inTreatment }

    function activateAndRefresh() {
        refreshAll () // needs to be first

        vTreatmentCreate.hdfTreatmentModeSet                = true
        vTreatmentCreate.substitutionFluidVolumeSet         = true
        vTreatmentCreate.bloodFlowRateSet                   = true
        vTreatmentCreate.dialysateFlowRateSet               = true
        vTreatmentCreate.treatmentDurationSet               = true
        vTreatmentCreate.ultrafiltrationVolumeSet           = true
        vTreatmentCreate.ufPreWeightSet                     = true
        vTreatmentCreate.ufEstimatedTargetWeightSet         = true
        vTreatmentCreate.heparinDispensingRateSet           = true
        vTreatmentCreate.heparinBolusVolumeSet              = true
        vTreatmentCreate.heparinDeliveryDurationSet         = true
        vTreatmentCreate.acidConcentrateSet                 = true
        vTreatmentCreate.dryBicarbCartSizeSet               = true
        vTreatmentCreate.dialyzerTypeSet                    = true
        vTreatmentCreate.dialysateTempSet                   = true
        vTreatmentCreate.sodiumSet                          = true
        vTreatmentCreate.bicarbonateSet                     = true
        vTreatmentCreate.fluidBolusVolumeSet                = true
        vTreatmentCreate.primeDiscardVolumeSet              = true
        vTreatmentCreate.rinsebackVolumeSet                 = true
        vTreatmentCreate.bloodPressureMeasureIntervalSet    = true
        vTreatmentCreate.hepatitusBStatusSet                = true
    }

    function refreshAll () {
        _preTreatmentCreateTreatmentSettings    .refreshAll()
        _preTreatmentCreatePatientPrescription  .refreshAll()
    }

    function clear () {
        _preTreatmentCreateTreatmentSettings    .clear()
        _preTreatmentCreatePatientPrescription  .clear()
        clearErrors()
        canEdit (true)
    }

    function clearErrors() {
        vTreatmentCreate.treatmentModalityRejectReason                      = Variables.noRejectReason
        vTreatmentCreate.hDFTreatmentModeRejectReason                       = Variables.noRejectReason
        vTreatmentCreate.bloodFlowRateRejectReason                          = Variables.noRejectReason
        vTreatmentCreate.dialysateFlowRateRejectReason                      = Variables.noRejectReason
        vTreatmentCreate.treatmentDurationRejectReason                      = Variables.noRejectReason
        vTreatmentCreate.heparinDeliveryDurationRejectReason                = Variables.noRejectReason
        vTreatmentCreate.heparinTypeRejectReason                            = Variables.noRejectReason
        vTreatmentCreate.dryBicarbCartSizeRejectReason                      = Variables.noRejectReason
        vTreatmentCreate.sodiumRejectReason                                 = Variables.noRejectReason
        vTreatmentCreate.bicarbonateRejectReason                            = Variables.noRejectReason
        vTreatmentCreate.dialyzerTypeRejectReason                           = Variables.noRejectReason
        vTreatmentCreate.fluidBolusVolumeRejectReason                       = Variables.noRejectReason
        vTreatmentCreate.bloodPressureMeasureIntervalRejectReason           = Variables.noRejectReason
        vTreatmentCreate.primeDiscardVolumeRejectReason                     = Variables.noRejectReason
        vTreatmentCreate.rinsebackVolumeRejectReason                        = Variables.noRejectReason
        vTreatmentCreate.hepatitusBStatusRejectReason                       = Variables.noRejectReason
        vTreatmentCreate.substitutionFluidVolumeRejectReason                = Variables.noRejectReason
        vTreatmentCreate.heparinBolusVolumeRejectReason                     = Variables.noRejectReason
        vTreatmentCreate.heparinDispensingRateRejectReason                  = Variables.noRejectReason
        vTreatmentCreate.dialysateTempRejectReason                          = Variables.noRejectReason
        vTreatmentCreate.acidConcentrateConversionFactorRejectionReason     = Variables.noRejectReason
        vTreatmentCreate.ufVolumeRejectionReason                            = Variables.noRejectReason
        vTreatmentCreate.ufPreWeightRejectionReason                         = Variables.noRejectReason
        vTreatmentCreate.ufEstimatedTargetWeightRejectionReason             = Variables.noRejectReason
        vTreatmentCreate.acidConcentrateIndexRejectionReason                = Variables.noRejectReason
    }

    function confirmReady () {
        return  _preTreatmentCreateTreatmentSettings    .ready() &&
                _preTreatmentCreatePatientPrescription  .ready()
    }

    function validate () {
        vTreatmentCreate                    .patientID = _preTreatmentCreateTreatmentSettings.patientID
        vPostTreatmentAdjustmentTreatmentLog.patientID = _preTreatmentCreateTreatmentSettings.patientID // store for the TreatmentLog

        vTreatmentCreate.doValidation       (        )
    }

    function confirm () { vTreatmentCreate.doConfirm() } /// TODO: Remove later.. keeping for now (only in popup) to get into main tx on device


    Connections { target: vTDOpMode
        function onPreTreatmentChanged( vValue ) {
            if ( vValue ) {
                _preTreatmentCreateTreatmentSettings    .setPresetParameters ()
                _preTreatmentCreatePatientPrescription  .setPresetParameters ()
                _prescriptionMenu.index = PreTreatmentCreateContent.PatientPrescription // reset tab to first tab on new treatment
            }
        }
    }

    Connections{ target: vTreatmentCreate
        function onDidValidationPass            ( ) {
            vPostTreatmentAdjustmentTreatmentLog.heparinDispensingRateOff = vTreatmentCreate.heparinDispensingRateOff   = ! vTreatmentCreate.heparinDispensingRate
            vPostTreatmentAdjustmentTreatmentLog.heparinBolusVolumeOff    = vTreatmentCreate.heparinBolusVolumeOff      = ! vTreatmentCreate.heparinBolusVolume
            activateAndRefresh() // refresh values on validation
            clearErrors()
        }
    }

    // TODO Phase 2
//    Connections {  target: _acidConcentrateAdjustment
//        function onAccepted () {
//            vTreatmentCreate.acidConcentrate      = _acidConcentrateComboBox.find(_acidConcentrateAdjustment.adjustment)
//            _acidConcentrateComboBox.currentIndex = vTreatmentCreate.acidConcentrate
//            vTreatmentCreate.acidConcentrateConversionFactor = vTreatmentRanges.acidConcentrateValues[vTreatmentCreate.acidConcentrate]
//        }
//    }


    HeparinRxAdjustment {   id: _heparinRxAdjustment;   editingEnabled: _root.editingEnabled    }
    UfVolumeAdjustment  {   id: _ufVolumeAdjustment;    editingEnabled: _root.editingEnabled    }

    MouseArea { // click outside to remove active focus and lower keyboard
        anchors.fill            : parent
        propagateComposedEvents : true
        onClicked               : focus = true   // grab focus here
    }

    MainMenu { id: _prescriptionMenu
        anchors {
            top             : parent.top
            topMargin       : Variables.defaultMargin
            left            : parent.left
        }

        width               : _root.width / 2.5
        index               : _root.currentIndex
        color               : Colors.transparent
        titlePixelSize      : 30
        model               : _model
        highlightWidth      : width / 2.5

        onItemPressed: function (vIndex) {
            _root.currentIndex = vIndex
        }

        ListModel { id: _model
            ListElement {   text: qsTr("Patient Prescription")      ; visible: true   }
            ListElement {   text: qsTr("Treatment Settings")        ; visible: true   }
        }
    }

    Line {
        anchors {
            bottom  : _prescriptionMenu.bottom
            right   : parent.right
            left    : parent.left
        }

        color   : Colors.panelBorderColor
    }

    BaseComboBox { id: _prescriptionDotMenu
        anchors {
            left                : _prescriptionMenu.right
            verticalCenter      : _prescriptionMenu.verticalCenter
            verticalCenterOffset: 5
        }

        model                   : ! vTreatmentCreate.parametersValidated ?  [ _root.selectRx,   _root.clearAll                      ]:
                                                                            [ _root.editRx,     _root.selectRx,     _root.clearAll  ]
        height                  : 50
        width                   : 75
        dropDownWidth           : 250
        delegateHeight          : 65
        iconAnchors.rightMargin : Variables.defaultMargin * 2
        displayText             : ""
        iconSource              : "qrc:/images/iMenuDot"
        backgroundColor         : Colors.transparent
        visible                 : ! vTDOpMode.inTreatment

        onActivated: {
            const selectedItem = model[currentIndex]

            // only send  AdjustParametersConfirmRequestData::eCancel when validated
            // Telling FW user is canceling confirm treatment parameters
            if ( vTreatmentCreate.parametersValidated ) { vTreatmentCreate.doCancel() }

            if      ( selectedItem === _root.editRx     )   { /*All parameters set to edit if parameters are validated */   }
            else if ( selectedItem === _root.selectRx   )   { print("TODO: Open and Select from Prescription Manager")      }
            else if ( selectedItem === _root.clearAll   )   { _root.clear()                                                 }
            else                                            {  /*Unknown state */                                           }
        }
    }

    Row { id: _qrRow
        height          : _root.cellHeight
        spacing         : Variables.defaultMargin
        anchors {
            left                :  parent.left
            leftMargin          : (_root.width / 2) + (30)
            verticalCenter      : _prescriptionMenu.verticalCenter
            verticalCenterOffset: -10
        }
        QRCode { id: _qrCode
            anchors.verticalCenter      : parent.verticalCenter
            qrcode          : vTreatmentCreate.txCode
            clear           : ! _root.visible
            height          : 65
            width           : height
        }

        Text { id: _txCode
            anchors.bottom  : _qrCode.bottom
            text            : vTreatmentCreate.txCode ? qsTr("Tx Code: ") + vTreatmentCreate.txCode : " "
            color           : "#DBE9FA"
            font.pixelSize  : Fonts.fontPixelButton
        }
    }

    Item { id: _view
        anchors {
            top         : _prescriptionMenu.bottom
            topMargin   : Variables.defaultMargin * 2
            left        : _root.left
            right       : _root.right
            bottom      : parent.bottom
        }

        PreTreatmentCreateTreatmentSettings   { id: _preTreatmentCreateTreatmentSettings
            visible         : _root.currentIndex === PreTreatmentCreateContent.PatientPrescription
            editingEnabled  : _root.editingEnabled
        }
        PreTreatmentCreatePatientPrescription { id: _preTreatmentCreatePatientPrescription;
            visible         : _root.currentIndex === PreTreatmentCreateContent.TreatmentSettings
            editingEnabled  : _root.editingEnabled

        }
    }
}
