import Quickshell
import Quickshell.Services.UPower
import QtQuick
import QtQuick.Layouts
import "../../shared" as Shared

Item {
    id: root

    implicitWidth: Shared.Theme.popoutWidth
    implicitHeight: col.implicitHeight + Shared.Theme.popoutPadding * 2

    readonly property var bat: UPower.displayDevice
    readonly property bool charging: bat
        && (bat.state === UPowerDeviceState.Charging
            || bat.state === UPowerDeviceState.FullyCharged
            || bat.state === UPowerDeviceState.PendingCharge)
    readonly property bool full: bat && bat.state === UPowerDeviceState.FullyCharged
    readonly property int pct: bat ? Math.round(bat.percentage * 100) : 0

    readonly property color levelColor: charging
        ? Shared.Theme.green
        : (pct <= 15 ? Shared.Theme.red
            : pct <= 30 ? Shared.Theme.yellow
            : Shared.Theme.blue)

    // seconds → "H:MM"
    function fmtTime(s) {
        if (!s || s <= 0) return "";
        const h = Math.floor(s / 3600);
        const m = Math.floor((s % 3600) / 60);
        return h + ":" + (m < 10 ? "0" + m : m);
    }

    PopoutBackground { anchors.fill: parent }
    MouseArea { anchors.fill: parent }

    ColumnLayout {
        id: col
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.verticalCenter: parent.verticalCenter
        anchors.margins: Shared.Theme.popoutPadding
        spacing: 6

        // ─── Header ───
        RowLayout {
            Layout.fillWidth: true
            spacing: 8
            Text {
                text: "Battery"
                color: Shared.Theme.text
                font.pixelSize: 18
                font.family: Shared.Theme.fontFamily
                font.bold: true
                Layout.fillWidth: true
            }
            Text {
                text: root.pct + "%"
                color: root.levelColor
                font.pixelSize: 18
                font.family: Shared.Theme.fontFamily
                font.bold: true
            }
        }

        // ─── Status line ───
        Text {
            Layout.fillWidth: true
            text: {
                if (!root.bat) return "No battery";
                if (root.full) return "Fully charged";
                if (root.charging) {
                    const t = root.fmtTime(root.bat.timeToFull);
                    return t ? "Charging · " + t + " to full" : "Charging";
                }
                const t = root.fmtTime(root.bat.timeToEmpty);
                return t ? "Discharging · " + t + " left" : "Discharging";
            }
            color: root.charging ? Shared.Theme.green : Shared.Theme.overlay0
            font.pixelSize: Shared.Theme.fontSmall
            font.family: Shared.Theme.fontFamily
        }

        // ─── separator ───
        Rectangle {
            Layout.fillWidth: true; height: 1; color: Shared.Theme.surface0
            Layout.topMargin: 4; Layout.bottomMargin: 4
        }

        // ─── Details ───
        InfoRow {
            label: "Health"
            value: root.bat ? Math.round(root.bat.healthPercentage) + "%" : ""
            visible: root.bat && root.bat.healthSupported
        }
        InfoRow {
            label: "Rate"
            value: root.bat ? Math.abs(root.bat.changeRate).toFixed(1) + " W" : ""
            visible: root.bat && root.bat.changeRate !== 0
        }

        // ─── Power profile ───
        Rectangle {
            visible: profileSelector.visible
            Layout.fillWidth: true; height: 1; color: Shared.Theme.surface0
            Layout.topMargin: 4; Layout.bottomMargin: 4
        }
        Text {
            visible: profileSelector.visible
            text: "Power profile"
            color: Shared.Theme.overlay0
            font.pixelSize: Shared.Theme.fontSize
            font.family: Shared.Theme.fontFamily
            font.bold: true
            Layout.bottomMargin: 2
        }
        RowLayout {
            id: profileSelector
            visible: Shared.Config.hasPowerProfiles && PowerProfiles.hasPerformanceProfile
            Layout.fillWidth: true
            spacing: 6

            ProfileButton { label: "Saver"; profile: PowerProfile.PowerSaver }
            ProfileButton { label: "Balanced"; profile: PowerProfile.Balanced }
            ProfileButton { label: "Perf"; profile: PowerProfile.Performance }
        }
    }

    component InfoRow: RowLayout {
        property string label
        property string value
        Layout.fillWidth: true
        implicitHeight: 22
        spacing: 10
        Text { text: parent.label; color: Shared.Theme.overlay0; font.pixelSize: Shared.Theme.fontSize; font.family: Shared.Theme.fontFamily; Layout.fillWidth: true }
        Text { text: parent.value; color: Shared.Theme.text; font.pixelSize: Shared.Theme.fontSize; font.family: Shared.Theme.fontFamily; font.bold: true }
    }

    component ProfileButton: Rectangle {
        property string label
        property int profile
        readonly property bool active: PowerProfiles.profile === profile

        Layout.fillWidth: true
        implicitHeight: 28
        radius: Shared.Theme.radiusSmall
        color: active ? Qt.alpha(Shared.Theme.focus, Shared.Theme.opacityLight) : Shared.Theme.surface0
        border.width: active ? 1 : 0
        border.color: Qt.alpha(Shared.Theme.focus, Shared.Theme.opacityMedium)

        Behavior on color { ColorAnimation { duration: Shared.Theme.animFast } }

        Text {
            anchors.centerIn: parent
            text: parent.label
            color: parent.active ? Shared.Theme.focusActive : Shared.Theme.subtext0
            font.pixelSize: Shared.Theme.fontSmall
            font.family: Shared.Theme.fontFamily
            font.bold: parent.active
        }

        MouseArea {
            anchors.fill: parent
            cursorShape: Qt.PointingHandCursor
            onClicked: PowerProfiles.profile = parent.profile
        }
    }
}
