/*!
 *
 * 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    TreatmentTrends.qml
 * \author  (last)      Stephen Quong
 * \date    (last)      01-Oct-2025
 * \author  (original)  Stephen Quong
 * \date    (original)  01-Oct-2025
 *
 */

// Qt
import QtQuick 2.12
import QtGraphicalEffects 1.12

// Project
//  Qml imports
import "qrc:/globals"
import "qrc:/components"
import "qrc:/pages/treatment/sections"

/*!
 * \brief   the Trends screen
 */
ScreenItem { id: _root
    objectName: "_TreatmentTrends"
    property alias isParamExpanded: _paramArea.isExpanded

    onVisibleChanged: {
        _paramList.positionViewAtBeginning()
        _historyList.positionViewAtBeginning()
    }

    QtObject { id: _private
        objectName                                  : "_private"
        readonly property int cellHeight            : 72
        readonly property int topHeaderHeight       : 80
        readonly property int labelWidth            : 300
        readonly property int scrollButtonWidth     : 40
        readonly property int paramAreaRightMargin  : 5
        readonly property int paramWidth            : 
            (_root.width - Variables.defaultMargin - labelWidth - scrollButtonWidth - paramAreaRightMargin - _expandButton.width) / 7
        readonly property int historyTimeWidth      : 50
    }

    component Header: Rectangle { id: _header
        objectName                      : "_header"
        property alias label            : _labelText.text
        property alias labelFontWeight  : _labelText.font.weight
        height                          : _private.topHeaderHeight
        radius                          : 10
        color                           : Colors.treatmentSectionHeader
        layer {
            enabled: true
            effect: DropShadow { id: _topHeaderShadow
                objectName      : "_topHeaderShadow"
                horizontalOffset: 2
                verticalOffset  : 2
                radius          : 12
                samples         : 32
                color           : "#50000000"
                source          : _header
            }
        }

        Text { id: _labelText
            objectName      : "_labelText"
            anchors {
                left            : parent.left
                leftMargin      : Variables.defaultMargin
                verticalCenter  : parent.verticalCenter
            }
            width               : _private.labelWidth
            height              : contentHeight
            color               : Colors.offWhite
            font {
                pixelSize   : 22
                weight      : Font.Medium
            }
            horizontalAlignment : Text.AlignLeft
        }
    }

    component ParameterLabel: Item { id: _labelItem
        objectName                      : "_labelItem"
        property alias label            : _labelText.text
        property alias labelFontWeight  : _labelText.font.weight
        property string unit            : ""
        property string subLabel        : ""
        property bool showDivider       : true
        anchors.left                    : parent.left
        width                           : _private.labelWidth
        height                          : _private.cellHeight

        Item { id: _labelArea
            objectName  : "_labelArea"
            anchors {
                left            : parent.left
                right           : parent.right
                verticalCenter  : parent.verticalCenter
            }
            height      : childrenRect.height

            Text { id: _labelText
                objectName          : "_labelText"
                anchors.left        : parent.left
                width               : contentWidth
                height              : contentHeight
                color               : Colors.offWhite
                font {
                    pixelSize   : 20
                    weight      : Font.Medium
                }
                horizontalAlignment : Text.AlignLeft
            }
            Text { id: _unitText
                objectName          : "_unitText"
                anchors {
                    left    : _labelText.right
                    baseline: _labelText.baseline
                }
                font {
                    pixelSize   : 18
                    weight      : Font.Thin
                }
                width               : text.length === 0 ? 0 : contentWidth
                height              : text.length === 0 ? 0 : contentHeight
                color               : Colors.textProgressBar
                horizontalAlignment : Text.AlignLeft
                text                : (_labelItem.unit.length !== 0) ? "  (%1)".arg(_labelItem.unit) : ""
            }
            Text { id: _subLabelText
                objectName          : "_subLabelText"
                anchors {
                    top     : _labelText.bottom
                    left    : _labelText.left
                }
                font {
                    pixelSize   : 18
                    weight      : Font.Thin
                    italic      : true
                }
                width               : text.length === 0 ? 0 : contentWidth
                height              : text.length === 0 ? 0 : contentHeight
                color               : Colors.textProgressBar
                horizontalAlignment : Text.AlignLeft
                text                : (_labelItem.subLabel.length !== 0) ? "(%1)".arg(_labelItem.subLabel) : ""
            }
        }

        Rectangle { id: _horizontalDivider
            objectName  : "_horizontalDivider"
            anchors {
                bottom  : parent.bottom
                left    : parent.left
                right   : parent.right
            }
            height      : 1
            color       : Colors.panelBorder
            visible     : _labelItem.showDivider
        }
    }

    component ValueText: Item { id: _valueItem
        objectName                      : "_valueItem"
        property alias value            : _valueText.text
        property alias valueFontWeight  : _valueText.font.weight
        property alias valueText        : _valueText
        property bool showDivider       : true
        width                           : _private.paramWidth
        height                          : _private.cellHeight
        enabled                         : true
        
        Text { id: _valueText
            objectName          : "_valueText"
            anchors.centerIn    : parent
            width               : contentWidth
            height              : contentHeight
            color               : Colors.offWhite
            font {
                pixelSize   : 24
                weight      : Font.DemiBold
            }
            horizontalAlignment : Text.AlignHCenter
            verticalAlignment   : Text.AlignVCenter
        }

        Rectangle { id: _horizontalDivider
            objectName  : "_horizontalDivider"
            anchors {
                bottom  : parent.bottom
                left    : parent.left
                right   : parent.right
            }
            height      : 1
            color       : Colors.panelBorder
            visible     : _valueItem.showDivider
        }
    }

    component LabelTime: Item { id: _labelTime
        objectName: "_labelTime"
        property string labelText: ""
        property string timeText: ""
        width: childrenRect.width

        Text { id: _label
            objectName: "_label"
            anchors{
                left            : parent.left
                verticalCenter  : parent.verticalCenter
            }
            width   : contentWidth
            color   : Colors.offWhite
            font.pixelSize       : 16
            text: _labelTime.labelText
        }

        Text { id: _timeText
            objectName: "_timeText"
            anchors{
                left      : _label.right
                baseline  : _label.baseline
            }
            width   : Math.max(50, contentWidth)
            color   : Colors.offWhite
            font {
                pixelSize       : 18
                weight          : Font.DemiBold
            }
            text: _labelTime.timeText
        }
    }

    Item { id: _contentArea
        objectName  : "_contentArea"
        anchors {
            fill    : parent
            margins : Variables.defaultMargin
        }

        Rectangle { id: _paramArea
            objectName              : "_paramArea"
            property bool isExpanded: true
            anchors {
                top     : parent.top
                bottom  : parent.bottom
                left    : parent.left
            }
            z                       : parent.z + 2
            width                   : _private.labelWidth + (_private.paramWidth * _paramList.visibleParamCount) +
                                        _private.scrollButtonWidth + (Variables.defaultMargin * 2)
            color                   : Colors.treatmentSectionMain
            radius                  : 10

            Behavior on width { NumberAnimation { duration: 200 } }

            Rectangle { id: _paramListBackground
                objectName: "_paramListBackground"
                anchors {
                    top     : parent.top
                    bottom  : _paramSideHeader.bottom
                    left    : _paramSideHeader.right
                    right   : parent.right
                }
                color   : Colors.panelBackground
                radius  : parent.radius

                Rectangle { id: _radiusCover
                    objectName: "_radiusCover"
                    anchors {
                        bottom  : parent.bottom
                        left    : parent.left
                    }
                    color   : parent.color
                    width   : parent.radius + 1
                    height  : width
                }

                Rectangle { id: _verticalDivider
                    objectName: "_verticalDivider"
                    anchors {
                        top     : parent.top
                        bottom  : parent.bottom
                        left    : parent.left
                    }
                    width: 1
                    color: Colors.panelBorder
                }
            }

            Header { id: _paramTopHeader
                objectName: "_paramTopHeader"
                anchors {
                    top     : parent.top
                    left    : parent.left
                    right   : parent.right
                }
                label           : qsTr("Parameters")
                labelFontWeight : Font.DemiBold
            }

            Column { id: _paramSideHeader
                objectName: "_paramSideHeader"
                anchors {
                    top         : _paramTopHeader.bottom
                    bottom      : parent.bottom
                    left        : parent.left
                    leftMargin  : Variables.defaultMargin
                }
                width: _private.labelWidth
                ParameterLabel { label: qsTr("Blood Pressure");         unit: Variables.unitPressure                                                }
                ParameterLabel { label: qsTr("Heart Rate");             unit: Variables.unitTextHeartBeat                                           }
                ParameterLabel { label: qsTr("UF Volume");              unit: Variables.unitVolume;         subLabel: qsTr("Cumulative Removed")    }
                ParameterLabel { label: qsTr("UF Rate");                unit: Variables.unitTextRate                                                }
                ParameterLabel { label: qsTr("Arterial Pressure");      unit: Variables.unitPressure                                                }
                ParameterLabel { label: qsTr("Venous Pressure");        unit: Variables.unitPressure                                                }
                ParameterLabel { label: qsTr("TMP");                    unit: Variables.unitPressure                                                }
                ParameterLabel { label: qsTr("Fluid Delivered");        unit: Variables.unitTextFluid;      subLabel: qsTr("Cumulative")            }
                ParameterLabel { label: qsTr("Blood Flow Rate");        unit: Variables.unitTextFlowRate                                            }
                ParameterLabel { label: qsTr("Dialysate Flow Rate");    unit: Variables.unitTextFlowRate                                            }
                ParameterLabel { label: qsTr("Temperature");            unit: Variables.unitTextTemperature                                         }
                ParameterLabel {
                    label       : qsTr("Conductivity")
                    unit        : Variables.unitTextDialCond
                    showDivider : false
                }
            }

            Item { id: _paramListArea
                objectName: "_paramListArea"
                anchors {
                    top     : parent.top
                    bottom  : parent.bottom
                    left    : _paramSideHeader.right
                    right   : _rightScrollButton.left
                }
                clip: true

                Behavior on width { NumberAnimation { duration: 200 } }

                ListView { id: _paramList
                    objectName: "_paramList"
                    readonly property int visibleParamCount: _paramArea.isExpanded ? 7 : 5
                    readonly property int modelCount: _paramList.count ?? 0
                    
                    anchors {
                        fill        : parent
                        rightMargin : (Math.max(0, visibleParamCount - _paramList.count) * _private.paramWidth)
                    }
                    orientation                 : ListView.Horizontal
                    layoutDirection             : Qt.RightToLeft
                    snapMode                    : ListView.SnapToItem
                    model                       : vTreatmentTrends.data
                    displayMarginBeginning      : visibleParamCount * _private.paramWidth
                    preferredHighlightBegin     : 0
                    preferredHighlightEnd       : _private.paramWidth
                    highlightRangeMode          : ListView.ApplyRange
                    highlightFollowsCurrentItem : true
                    addDisplaced                : Transition { NumberAnimation { properties: "x"; duration: 200 } }
                    delegate: Column { id: _paramListDelegate
                        ValueText { id: _timestampValue
                            objectName      : "_timestampValue"
                            height          : _private.topHeaderHeight
                            value           : Qt.formatTime(timestamp, "hh:mm")
                            valueFontWeight : Font.Bold
                            showDivider     : false

                            Text { id: _lastTimeText
                                objectName: "_lastTimeText"
                                anchors {
                                    top             : parent.top
                                    topMargin       : 10
                                    horizontalCenter: parent.horizontalCenter
                                }
                                font.pixelSize  : 14
                                color           : Colors.ufVolumeGoalText
                                height          : contentHeight
                                text            : qsTr("Last Time")
                                visible         : model.index === 0
                            }
                        }
                        ValueText { id: _bloodpressureValue
                            objectName  : "_bloodpressureValue"
                            value       : "%1/%2".arg(systolic ?? "--").arg(diastolic ?? "--")
                        }
                        ValueText { id: _pulseRateValue
                            objectName  : "_pulseRateValue"
                            value       : pulseRate ?? "--"
                        }
                        ValueText { id: _ufVolumeRemovedValue
                            objectName  : "_ufVolumeRemovedValue"
                            value       : ufVolumeRemoved != undefined ? ufVolumeRemoved.toFixed(Variables.ultrafiltrationPrecision) : "--"
                        }
                        ValueText { id: _ufRateValue
                            objectName  : "_ufRateValue"
                            value       : ufRate != undefined ? ufRate.toFixed(Variables.ultrafiltrationPrecision) : "--"
                        }
                        ValueText { id: _arterialPressureValue
                            objectName  : "_arterialPressureValue"
                            value       : arterialPressure ?? "--"
                        }
                        ValueText { id: _venousPressureValue
                            objectName  : "_venousPressureValue"
                            value       : venousPressure ?? "--"
                        }
                        ValueText { id: _tmpValue
                            objectName  : "_tmpValue"
                            value       : tmp ?? "--"
                        }
                        ValueText { id: _bolusCumulativeDeliveredValue
                            objectName  : "_bolusCumulativeDeliveredValue"
                            value       : bolusCumulativeDelivered ?? "--"
                        }
                        ValueText { id: _bloodFlowRateValue
                            objectName  : "_bloodFlowRateValue"
                            value       : bloodFlowRate != undefined ? bloodFlowRate.toFixed(Variables.bloodFlowPrecision) : "--"
                        }
                        ValueText { id: _dialysateFlowRateValue
                            objectName  : "_dialysateFlowRateValue"
                            value       : dialysateFlowRate != undefined ? dialysateFlowRate.toFixed(Variables.dialysateFlowPrecision) : "--"
                        }
                        ValueText { id: _dialysateTemperatureValue
                            objectName  : "_dialysateTemperatureValue"
                            value       : dialysateTemperature != undefined ? dialysateTemperature.toFixed(Variables.dialysateTempPrecision) : "--"
                        }
                        ValueText { id: _conductivityValue
                            objectName  : "_conductivityValue"
                            value       : conductivity != undefined ? conductivity.toFixed(Variables.dialysateCondPrecision) : "--"
                            showDivider : false
                        }
                    }

                    Behavior on contentX { NumberAnimation { duration: 200 } }

                    onModelCountChanged: { positionViewAtBeginning() }
                }
            }

            ScrollBar2 { id: _scrollbar
                objectName: "_scrollbar"
                anchors {
                    bottom          : parent.bottom
                    bottomMargin    : 10
                    left            : _paramListArea.left
                    leftMargin      : Variables.defaultMargin
                    right           : parent.right
                    rightMargin     : Variables.defaultMargin
                }
                height      : 5
                direction   : ScrollBar2.Horizontal
                scrollColor : "#606060"
                flickable   : _paramList
                opacity     : _paramList.count > _paramList.visibleParamCount
                                || _paramList.flicking || _paramList.dragging ? 1 : 0

                Behavior on opacity { NumberAnimation { duration: 200 } }
            }

            ArrowButton { id: _leftScrollButton
                objectName: "_leftScrollButton"
                anchors {
                    right           : _paramListArea.left
                    verticalCenter  : _paramTopHeader.verticalCenter
                }
                touchable   : _paramList.atXBeginning === false
                iconImage   : touchable ? "qrc:/images/iArrowLeft" : "qrc:/images/iArrowLeftDisabled"
                isDefault   : false
                borderColor : Colors.transparent

                onClicked: {
                    if (_paramList.atXBeginning === false) {
                        _paramList.contentX = Math.max(-(_paramList.contentWidth), _paramList.contentX - _private.paramWidth)
                    }
                }
            }

            ArrowButton { id: _rightScrollButton
                objectName: "_rightScrollButton"
                anchors {
                    right           : parent.right
                    rightMargin     : _private.paramAreaRightMargin // Variables.defaultMargin
                    verticalCenter  : _paramTopHeader.verticalCenter
                }
                touchable   : _paramList.atXEnd === false
                iconImage   : touchable ? "qrc:/images/iArrowRight" : "qrc:/images/iArrowRightDisabled"
                isDefault   : false
                borderColor : Colors.transparent

                onClicked: {
                    if (_paramList.atXEnd === false) {
                        _paramList.contentX = Math.min(-(_paramList.visibleParamCount * _private.paramWidth), _paramList.contentX + _private.paramWidth)
                    }
                }
            }
        }

        TouchRect { id: _expandButton
            objectName: "_expandButton"
            anchors {
                left            : _paramArea.right
                leftMargin      : -(width / 2)
                verticalCenter  : _paramArea.verticalCenter
            }
            z               : _paramArea.z - 1
            width           : 80
            height          : width
            radius          : height
            border.color    : Colors.transparent
            backgroundColor : Colors.backgroundButtonSelect

            onPressed: {
                _paramArea.isExpanded = ! _paramArea.isExpanded
            }

            Image { id: _iconImage
                objectName: "_iconImage"
                anchors {
                    horizontalCenter        :  parent.horizontalCenter
                    horizontalCenterOffset  :  (parent.width/4) - (width/8)
                    verticalCenter          :  parent.verticalCenter
                }
                height  : 35
                width   : 35
                fillMode: Image.PreserveAspectFit
                source  : _paramArea.isExpanded ? "qrc:/images/iChevronLeft" : "qrc:/images/iChevronRight"
            }
        }

        Rectangle { id: _historyArea
            objectName: "_historyArea"
            anchors {
                top         : _paramArea.top
                bottom      : _paramArea.bottom
                left        : _expandButton.right
                leftMargin  : Variables.defaultMargin
            }
            width   : _private.paramWidth * 2 - Variables.defaultMargin
            radius  : _paramListBackground.radius
            color   : _paramListBackground.color
            opacity : _paramArea.isExpanded ? 0 : 1

            Behavior on opacity { NumberAnimation { duration: 200 } }

            Header { id: _historyHeader
                objectName: "_historyHeader"
                anchors {
                    top     : parent.top
                    left    : parent.left
                    right   : parent.right
                }
                label           : qsTr("Treatment History")
                labelFontWeight : Font.DemiBold
            }

            Rectangle { id: _timeArea
                objectName: "_timeArea"
                anchors {
                    top         : _historyHeader.bottom
                    topMargin   : Variables.defaultMargin
                    left        : parent.left
                    leftMargin  : Variables.defaultMargin
                    right       : parent.right
                    rightMargin : anchors.leftMargin
                }
                height  : 60
                color   : Colors.panelBackgroundColor
                border {
                    width: 1
                    color: Colors.panelBorderColor
                }
                radius  : 8.5

                Item { id: _timeContainer
                    anchors {
                        top: parent.top
                        bottom: parent.bottom
                        horizontalCenter: parent.horizontalCenter
                    }
                    width: childrenRect.width

                    LabelTime { id: _startTime
                        objectName: "_startTime"
                        anchors.left: parent.left
                        height: parent.height
                        labelText: qsTr("Start Time: ")
                        timeText: Qt.formatDateTime(vTreatmentTrends.time_Start, "hh:mm")
                    }

                    LabelTime { id: _elapsedTime
                        objectName: "_elapsedTime"
                        readonly property int hours: vTreatmentTrends.time_Elapsed / 3600
                        readonly property int mins: (vTreatmentTrends.time_Elapsed % 3600) / 60
                        anchors {
                            left: _startTime.right
                            leftMargin: Variables.defaultMargin
                        }
                        height: parent.height
                        labelText: qsTr("Time Elapsed (hrs): ")
                        timeText: "%1:%2".arg(hours < 10 ? "0" + hours : hours).arg(mins < 10 ? "0" + mins : mins)
                    }
                }
            }

            ListView { id: _historyList
                objectName: "_historyList"
                readonly property int modelCount: _paramList.count ?? 0

                anchors {
                    top         : _timeArea.bottom
                    topMargin   : 10
                    bottom      : parent.bottom
                    bottomMargin: Variables.defaultMargin
                    left        : _timeArea.left
                    right       : _timeArea.right
                }
                model: vTreatmentTrends.history
                clip: true
                addDisplaced: Transition { NumberAnimation { properties: "y"; duration: 200 } }
                delegate: Item { id: _historyItem
                    objectName: "_historyItem"
                    width: _historyList.width
                    height: 50

                    Text { id: _time
                        objectName: "_time"
                        anchors {
                            top: parent.top
                            bottom: parent.bottom
                            left: parent.left
                        }
                        width: _private.historyTimeWidth
                        font.pixelSize: 20
                        font.weight: Font.Medium
                        color: _historyText.color
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                        text: Qt.formatDateTime(timestamp, "hh:mm")
                    }

                    Rectangle { id: _historyDivider
                        objectName: "_historyDivider"
                        anchors {
                            top: parent.top
                            bottom: parent.bottom
                            left: _time.right
                            leftMargin: Variables.defaultMargin
                        }
                        width: 1
                        color: Colors.panelBorder
                    }

                    Text { id: _historyText
                        objectName: "_historyText"
                        anchors {
                            top: parent.top
                            bottom: parent.bottom
                            left: _historyDivider.right
                            leftMargin: Variables.defaultMargin
                            right: parent.right
                        }
                        font.pixelSize: 18
                        color: Colors.offWhite
                        horizontalAlignment: Text.AlignLeft
                        verticalAlignment: Text.AlignVCenter
                        elide: Text.ElideRight
                        text: entryID ? "(%1: %2) %3".arg(qsTr("ID")).arg(entryID).arg(message) : message
                    }
                }

                onModelCountChanged: { positionViewAtBeginning() }
            }

            ScrollBar2 { id: _historyScrollbar
                objectName: "_historyScrollbar"
                anchors {
                    top         : _historyList.top
                    bottom      : _historyList.bottom
                    right       : parent.right
                    rightMargin : 5
                }
                width       : 5
                scrollColor : "#606060"
                direction   : ScrollBar2.Vertical
                flickable   : _historyList
                opacity     : _historyList.contentHeight > _historyList.height
                                || _historyList.flicking || _historyList.dragging ? 1 : 0

                Behavior on opacity { NumberAnimation { duration: 200 } }
            }
        }
    }
}
