/*!
 *
 * Copyright (c) 2025-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    TreatmentHeparin.qml
 * \author  (last)      Nico Ramirez
 * \date    (last)      2-Dec-2025
 * \author  (original)  Nico Ramirez
 * \date    (original)  2-Dec-2025
 *
 */

// Qt
import QtQuick 2.12

// Project

//  Qml imports
import "qrc:/globals"
import "qrc:/components"
import "qrc:/compounds"
import "qrc:/pages/treatment"

/*!
 * \brief   Treatment Screen Heparin Management section
 */
ScreenItem  { id: _root
    readonly property bool isOff            : vTDTreatmentStates.hpOff
    readonly property bool isStopped        : vTDTreatmentStates.hpStopped
    readonly property bool isPaused         : vTDTreatmentStates.hpPaused
    readonly property bool isBolus          : vTDTreatmentStates.hpInitial_bolus
    readonly property bool isDispensing     : vTDTreatmentStates.hpDispensing
    readonly property bool isCompleted      : vTDTreatmentStates.hpCompleted
    readonly property bool isEmpty          : vTDTreatmentStates.hpEmpty
    readonly property bool isRejected       : vTreatmentAdjustmentHeparin.adjustment_Accepted
    readonly property bool isTxRunning      : vTDTreatmentStates.txDialysis


    readonly property bool   deliveryOff    : vTreatmentCreate.heparinDispensingRate === 0
    readonly property string buttonText     : isDispensing  ? qsTr("Pause")   :
                                              isPaused      ? qsTr("Resume")  : qsTr("Pause")

    readonly property string statusText     : isDispensing  ? qsTr("Active")    :
                                              isPaused      ? qsTr("Pause")     :
                                              isCompleted   ? qsTr("Complete")  :  qsTr("Active")

    readonly property var titles        : [  qsTr("Heparin Type"),                                              qsTr("Dispensing Rate"),                qsTr("Bolus Volume"),                   qsTr("Stop Time")                   ]
    readonly property var units         : [ Variables.unitHeparinType,                                          Variables.unitTextDispensingRate,       Variables.unitTextDispensingRate,       Variables.unitTextDuration          ]
    readonly property var values        : [ vTreatmentRanges.heparinTypeOptions[vTreatmentCreate.heparinType],  vTreatmentCreate.heparinDispensingRate, vTreatmentCreate.heparinBolusVolume,    vTreatmentCreate.heparinStopTime    ]

    readonly property real cumulative       : vTreatmentHeparin.cumulative
    readonly property real target           : vTreatmentHeparin.target
    readonly property string timeRemaining  : vTreatmentHeparin.timeRemaining

    signal idleTimeout()

    function statusColor ( vHeaderBar = false ) {
        return  deliveryOff     ?   Colors.transparent      :
                isDispensing    ?   Colors.statusActive     :
                isPaused        ?   Colors.statusPaused     :
                isCompleted     ?   vHeaderBar  ?   Colors.statusComplete       :
                                                    Colors.statusTextComplete   :
                                    Colors.transparent
    }

    enum HeparinPrescription{
        HeparinType,
        DispensingRate,
        BolusVolume,
        StopTime
    }

    component HeparinContainer: TreatmentSection { id: _heparinContainer
        color           : Colors.panelBackgroundColor
        header.color    : Colors.heparinSectionHeader
        enableDropShadow: false
        header {
            showEdit : false
            titleLeftMargin: Variables.defaultMargin * 3
        }
        contentArea.anchors {
            topMargin   : 0
            leftMargin  : Variables.defaultMargin * 2
            rightMargin : Variables.defaultMargin * 2
        }
        border {
            width: 1
            color: Colors.heparinPanelBorderColor
        }
        header.border {
            width: 1
            color: Colors.heparinPanelBorderColor
        }
    }

    Connections { target: vTreatmentAdjustmentHeparin
        function onAdjustmentTriggered              ( vValue ) {
            _notification.text = vTreatmentAdjustmentHeparin.adjustment_Accepted ? "" :
                                                                                   vTreatmentAdjustmentHeparin.adjustment_ReasonText
        }
    }

    Connections { target:   vTDTreatmentStates
        function onHeparinChanged                   ( vValue ) {
            vListModel.setHeaderbarStatusColor(HeaderBar.Heparin, _root.statusColor(true).toString())
        }
    }

    IdleTimer {id: _idleTimer
        anchors.fill        : parent

        onIdle: {
            _root.idleTimeout()
        }
    }

    Row { id: _row
        objectName  : "_row"
        spacing     : Variables.defaultMargin * 5

        anchors {
            fill        : parent
            topMargin   : Variables.defaultMargin * 5
            leftMargin  : Variables.defaultMargin * 5
            rightMargin : Variables.defaultMargin * 5
        }

        readonly property int cellWidth         : width / 2 - ( spacing / 2 ) // 2 items for the row and subtract spacing for widths
        readonly property int cellHeight        : height / 2
        readonly property int prescriptionCount : _root.titles.length

        HeparinContainer { id: _heparinPrescription
            objectName      : "_heparinPrescription"
            header.title    : qsTr("Heparin Prescription" )
            width           : _row.cellWidth
            height          : _row.cellHeight

            contentItem : Column { id :_heparinPrescriptionContent
                Repeater {
                    model: _row.prescriptionCount
                    delegate: LabelUnitContainer {
                        width           : parent.width
                        height          : parent.height / _row.prescriptionCount
                        border.width    : 0
                        color           :  Colors.transparent
                        text            : _root.titles[index]
                        unitText        : _root.units[index]
                        titleFontSize   : Fonts.fontPixelContainerTitleSmall
                        unitFontSize    : Fonts.fontPixelContainerUnitSmall

                        contentItem : Text{ id: _value
                            anchors.centerIn: parent
                            color           : Colors.offWhite
                            font.pixelSize  : Fonts.fontPixelHeparin
                            text            : _root.deliveryOff ? qsTr("OFF") :   index === TreatmentHeparin.DispensingRate ||
                                                                            index === TreatmentHeparin.BolusVolume ?     _root.values[index].toFixed(Variables.heparinPrecision) :
                                                                                                                         _root.values[index]
                        }
                        // Bottom border, except for last item
                        Rectangle { id: _separator
                            anchors {
                                left        : parent.left
                                leftMargin  : Variables.defaultMargin
                                right       : parent.right
                                rightMargin : Variables.defaultMargin
                                bottom      : parent.bottom
                            }
                            height          : 1
                            color           : Colors.panelBorderColor
                            visible         : index < titles.length - 1   // hide for last item
                        }
                    }
                }
            }
        }

        HeparinContainer { id: _heparinDelivery
            objectName      : "_heparinDelivery"
            header.title    : qsTr("Heparin Delivery" )
            width           : _row.cellWidth
            height          : _row.cellHeight

            contentItem : Item { id: _content
                anchors.fill : parent

                TouchRect { id: _heparinButton
                    anchors {
                        left            : parent.left
                        leftMargin      : Variables.defaultMargin
                        bottom          : parent.bottom
                        bottomMargin    : Variables.defaultMargin * 1.5
                    }

                    width           : Variables.defaultButtonWidth
                    height          : Variables.defaultButtonHeight
                    radius          : 9
                    text.textFormat : Text.RichText
                    text.text       : _root.buttonText
                    isDefault       : true
                    visible         : ! _root.deliveryOff && ( _root.isDispensing || _root.isPaused )
                    text.font.weight: Font.DemiBold

                    onPressed : {
                        if ( _root.isPaused     ) vTreatmentAdjustmentHeparin.doResume()
                        if ( _root.isDispensing ) vTreatmentAdjustmentHeparin.doPause ()
                        _idleTimer.reset()
                    }
                }

                Rectangle { id: _status
                    anchors {
                        top         : parent.top
                        topMargin   : Variables.defaultMargin * 1.5
                        right       : parent.right
                    }
                    visible : ! _root.deliveryOff && ( _root.isDispensing || _root.isPaused || _root.isCompleted )
                    width   : 100
                    height  : 30
                    radius  : height
                    color   : statusColor()
                    Text { id: _statusText
                        anchors.centerIn: parent
                        text            : _root.statusText
                        color           : Colors.white
                        font.pixelSize  : Fonts.fontPixelContainerUnitSmall
                        font.weight     : Font.DemiBold
                    }
                }

                Item {
                    anchors {
                        top         : parent.top
                        topMargin   : Variables.defaultMargin * 1.5
                        left        : parent.left
                        leftMargin  : Variables.defaultMargin
                    }

                    Text { id: _timeRemainingTitle
                        anchors {
                            top     : parent.top
                            left    : parent.left
                        }
                        text            : qsTr("Time Remaining")
                        color           : Colors.white
                        font.pixelSize  : Fonts.fontPixelHeparin
                        font.weight     : Font.Medium
                    }

                    Text { id: _timeRemaining
                        anchors {
                            top         : _timeRemainingTitle.bottom
                            topMargin   : _root.deliveryOff ? Variables.defaultMargin : Variables.defaultMargin / 2
                            left        : parent.left
                        }
                        text            : _root.deliveryOff ? ("%1 : %2").arg(Variables.emptyEntry).arg(Variables.emptyEntry) : _root.timeRemaining
                        color           : _root.deliveryOff ? Colors.white : _root.isPaused    ? Colors.statusPaused : Colors.white
                        font.pixelSize  : _root.deliveryOff ? Fonts.fontPixelHeparin : Fonts.fontPixelHeparinTime
                        font.weight     : Font.DemiBold
                    }

                    Text { id: _hrsMinsText
                        anchors {
                            top         : _timeRemaining.bottom
                            left        : parent.left
                            leftMargin  : 5
                        }
                        width           : 70
                        text            : Variables.unitTextHrs
                        color           : Colors.white
                        font.pixelSize  : Fonts.fontPixelContainerUnit
                        font.weight     : Font.Thin
                    }

                    Text { id: _hrsMinsText1
                        anchors {
                            top         : _timeRemaining.bottom
                            left        : _hrsMinsText.right
                            leftMargin  : 5
                        }
                        width           : _timeRemaining.contentWidth / 2
                        text            : Variables.unitTextMins
                        color           : Colors.white
                        font.pixelSize  : Fonts.fontPixelContainerUnit
                        font.weight     : Font.Thin
                    }
                }

                Column { id: _deliveryColumn
                    anchors {
                        right: parent.right
                        top  : parent.top
                    }
                    topPadding  : Variables.defaultMargin * 9.5
                    width       : parent.width * 0.7
                    height      : _content.height * 0.7

                    ProgressBar { id: _progressbar
                        width       : parent.width
                        height      : 20
                        decimal     : Variables.heparinDeliveryPrecision
                        minimum     : 0
                        maximum     : _root.deliveryOff ? 0 : _root.target
                        value       : _root.deliveryOff ? 0 : _root.cumulative
                        unitText    : Variables.unitTextFluid
                        color       : _root.isPaused ? Colors.statusPaused : Colors.progressBarUltrafiltration
                        radius      : height
                        showMarker  : false
                        progress.opacity: _root.isPaused ? 0.5 : 1

                        minText.color: "#818181"
                        minText.font {
                            pixelSize   : 18
                            weight      : Font.Normal
                        }

                        maxText.color: "#818181"
                        maxText.font {
                            pixelSize   : 18
                            weight      : Font.Normal
                        }

                        Text { id: _valueText
                            anchors {
                                bottom      : parent.top
                                bottomMargin: Variables.defaultMargin
                                right       : parent.right
                            }
                            text            : ("%1 %2").arg(_root.deliveryOff ? Variables.emptyEntry :
                                                                                _root.cumulative.toFixed(Variables.heparinDeliveryPrecision)).arg(qsTr(Variables.unitTextFluid))
                            color           : _root.deliveryOff ? Colors.white : _root.isPaused ? Colors.statusPaused : Colors.white
                            font.pixelSize  : Fonts.fontPixelHeparin
                            font.weight     : Font.DemiBold
                        }

                        Text { id: _heparinDeliveredText
                            anchors {
                                top         : parent.bottom
                                topMargin   : Variables.defaultMargin * 2.5
                                right       : parent.right
                            }
                            text            : qsTr("Heparin Delivered")
                            color           : Colors.textTextRectLabel
                            font.pixelSize  : 20
                            font.weight     : Font.Medium
                        }
                    }
                }
            }
        }
    }

    NotificationBarSmall { id: _notification
        visible     : text
        color       : Colors.transparent
        textColor   : Colors.white
        imageSource : ""
        text        : ""
        anchors.bottomMargin: _root.notificationMargin
    }


}
