import Quickshell
import Quickshell.Bluetooth
import QtQuick
import QtQuick.Layouts
import QtQuick.Window
import "../../shared" as Shared

// Full bluetooth manager: adapter power, scan/discovery, and per-device
// pair / connect / disconnect / trust / forget. Uses Quickshell.Bluetooth (BlueZ).
Item {
    id: root

    implicitWidth: Shared.Theme.popoutWidth
    implicitHeight: Math.min(content.implicitHeight + Shared.Theme.popoutPadding * 2, Screen.height - 32)

    readonly property BluetoothAdapter adapter: Bluetooth.defaultAdapter
    readonly property bool powered: adapter ? adapter.enabled : false
    readonly property bool scanning: adapter ? adapter.discovering : false

    // Device list ordered connected → paired → discovered, then alphabetical.
    property var sortedDevices: []
    function resort() {
        const devs = (Bluetooth.devices ? Bluetooth.devices.values : []).slice();
        function rank(d) { return d.connected ? 0 : ((d.paired || d.bonded) ? 1 : 2); }
        devs.sort(function (a, b) {
            const ra = rank(a), rb = rank(b);
            if (ra !== rb) return ra - rb;
            const na = (a.deviceName || a.name || a.address || "").toLowerCase();
            const nb = (b.deviceName || b.name || b.address || "").toLowerCase();
            return na < nb ? -1 : (na > nb ? 1 : 0);
        });
        sortedDevices = devs;
    }
    Component.onCompleted: resort()
    // Re-sort while open so connect/pair state churn (and pair/forget) reorders
    // the list (open-only timer, consistent with SystemPopout's polling).
    Timer { interval: 1500; running: root.visible; repeat: true; onTriggered: root.resort() }

    function deviceGlyph(d) {
        const ic = (d.icon || "").toLowerCase();
        if (ic.indexOf("headset") >= 0 || ic.indexOf("headphone") >= 0 || ic.indexOf("audio-card") >= 0) return "\u{f02cb}"; // headphones
        if (ic.indexOf("audio") >= 0 || ic.indexOf("speaker") >= 0) return "\u{f04c3}"; // speaker
        if (ic.indexOf("phone") >= 0) return "\u{f011c}";   // cellphone
        if (ic.indexOf("mouse") >= 0) return "\u{f037d}";   // mouse
        if (ic.indexOf("keyboard") >= 0) return "\u{f030c}"; // keyboard
        if (ic.indexOf("watch") >= 0) return "\u{f0b3b}";   // watch
        if (ic.indexOf("input-gaming") >= 0) return "\u{f0eb5}"; // controller
        return "\u{f00af}"; // generic bluetooth
    }
    function batteryPct(d) { return Math.round(d.battery > 1 ? d.battery : d.battery * 100); }

    PopoutBackground { anchors.fill: parent }
    MouseArea { anchors.fill: parent }   // swallow clicks (don't close on inside-click)

    // ── A single device row ───────────────────────────────────
    component DeviceRow: Rectangle {
        required property var modelData
        readonly property var dev: modelData

        Layout.fillWidth: true
        implicitHeight: 42
        radius: Shared.Theme.radiusSmall
        color: rowMouse.containsMouse ? Shared.Theme.surface1 : Shared.Theme.surface0

        // Primary action covers the whole row; the action icons below sit on top.
        MouseArea {
            id: rowMouse
            anchors.fill: parent
            hoverEnabled: true
            cursorShape: Qt.PointingHandCursor
            onClicked: {
                if (dev.pairing) { dev.cancelPair(); return; }
                if (dev.paired || dev.bonded) {
                    if (dev.connected) dev.disconnect(); else dev.connect();
                } else {
                    dev.pair();
                }
            }
        }

        RowLayout {
            anchors.fill: parent
            anchors.leftMargin: 10
            anchors.rightMargin: 8
            spacing: 8

            Text {
                text: root.deviceGlyph(dev)
                color: dev.connected ? Shared.Theme.green : Shared.Theme.subtext0
                font.pixelSize: 16
                font.family: Shared.Theme.iconFont
            }

            ColumnLayout {
                Layout.fillWidth: true
                spacing: 0
                Text {
                    text: dev.deviceName || dev.name || dev.address
                    color: Shared.Theme.text
                    font.pixelSize: 12
                    font.family: Shared.Theme.fontFamily
                    elide: Text.ElideRight
                    Layout.fillWidth: true
                }
                Text {
                    readonly property string st: dev.pairing ? "Pairing…"
                        : dev.connected ? "Connected"
                        : (dev.paired || dev.bonded) ? "Paired" : "Available"
                    text: dev.batteryAvailable ? st + "  •  " + root.batteryPct(dev) + "%" : st
                    color: dev.connected ? Shared.Theme.green
                        : (dev.pairing ? Shared.Theme.yellow : Shared.Theme.overlay0)
                    font.pixelSize: 9
                    font.family: Shared.Theme.fontFamily
                }
            }

            // trust toggle (paired devices only)
            Text {
                visible: dev.paired || dev.bonded
                text: dev.trusted ? "\u{f04ce}" : "\u{f04d2}"  // star / star-outline
                color: dev.trusted ? Shared.Theme.yellow : Shared.Theme.overlay0
                font.pixelSize: 14
                font.family: Shared.Theme.iconFont
                MouseArea {
                    anchors.fill: parent
                    cursorShape: Qt.PointingHandCursor
                    onClicked: dev.trusted = !dev.trusted
                }
            }
            // forget (paired devices only)
            Text {
                visible: dev.paired || dev.bonded
                text: "\u{f01b4}"  // delete
                color: Shared.Theme.red
                font.pixelSize: 14
                font.family: Shared.Theme.iconFont
                MouseArea {
                    anchors.fill: parent
                    cursorShape: Qt.PointingHandCursor
                    onClicked: dev.forget()
                }
            }
        }
    }

    Flickable {
        id: flick
        anchors.fill: parent
        anchors.margins: Shared.Theme.popoutPadding
        contentHeight: content.implicitHeight
        clip: true
        boundsBehavior: Flickable.StopAtBounds

        ColumnLayout {
            id: content
            width: flick.width
            spacing: 10

            // ── Header: title + power toggle ──────────────────
            RowLayout {
                Layout.fillWidth: true
                Text {
                    text: "Bluetooth"
                    color: Shared.Theme.text
                    font.pixelSize: 16
                    font.family: Shared.Theme.fontFamily
                    font.bold: true
                    Layout.fillWidth: true
                }
                Rectangle {
                    width: 40; height: 22; radius: 11
                    color: root.powered ? Shared.Theme.green : Shared.Theme.surface2
                    opacity: root.adapter ? 1.0 : 0.4
                    Behavior on color { ColorAnimation { duration: Shared.Theme.animFast } }
                    Rectangle {
                        width: 16; height: 16; radius: 8; y: 3
                        x: root.powered ? parent.width - width - 3 : 3
                        color: Shared.Theme.base
                        Behavior on x { NumberAnimation { duration: Shared.Theme.animFast; easing.type: Easing.OutCubic } }
                    }
                    MouseArea {
                        anchors.fill: parent
                        enabled: root.adapter !== null
                        cursorShape: Qt.PointingHandCursor
                        onClicked: root.adapter.enabled = !root.adapter.enabled
                    }
                }
            }
            Text {
                visible: root.adapter !== null
                text: root.adapter ? root.adapter.name : ""
                color: Shared.Theme.overlay0
                font.pixelSize: 9
                font.family: Shared.Theme.fontFamily
            }

            // No adapter present
            Text {
                visible: root.adapter === null
                text: "No bluetooth adapter found"
                color: Shared.Theme.overlay0
                font.pixelSize: 12
                font.family: Shared.Theme.fontFamily
                topPadding: 8
            }

            // ── Scan toggle ───────────────────────────────────
            Rectangle {
                visible: root.powered
                Layout.fillWidth: true
                implicitHeight: 32
                radius: Shared.Theme.radiusSmall
                color: scanMouse.containsMouse ? Shared.Theme.surface1 : Shared.Theme.surface0
                RowLayout {
                    anchors.fill: parent
                    anchors.leftMargin: 10
                    anchors.rightMargin: 10
                    Text {
                        text: root.scanning ? "Scanning…" : "Scan for devices"
                        color: root.scanning ? Shared.Theme.sky : Shared.Theme.text
                        font.pixelSize: 11
                        font.family: Shared.Theme.fontFamily
                        Layout.fillWidth: true
                    }
                    Rectangle {
                        visible: root.scanning
                        width: 8; height: 8; radius: 4
                        color: Shared.Theme.sky
                        SequentialAnimation on opacity {
                            running: root.scanning; loops: Animation.Infinite
                            NumberAnimation { from: 1.0; to: 0.2; duration: 600 }
                            NumberAnimation { from: 0.2; to: 1.0; duration: 600 }
                        }
                    }
                    Text {
                        visible: !root.scanning
                        text: "\u{f0349}"  // magnify
                        color: Shared.Theme.overlay0
                        font.pixelSize: 13
                        font.family: Shared.Theme.iconFont
                    }
                }
                MouseArea {
                    id: scanMouse
                    anchors.fill: parent
                    hoverEnabled: true
                    cursorShape: Qt.PointingHandCursor
                    onClicked: if (root.adapter) root.adapter.discovering = !root.adapter.discovering
                }
            }

            // ── Device list ───────────────────────────────────
            Repeater {
                model: root.sortedDevices
                delegate: DeviceRow {}
            }

            // Empty state
            Text {
                visible: root.powered && root.sortedDevices.length === 0
                text: root.scanning ? "Searching…" : "No devices — start a scan"
                color: Shared.Theme.overlay0
                font.pixelSize: 11
                font.family: Shared.Theme.fontFamily
                Layout.alignment: Qt.AlignHCenter
                topPadding: 8
                bottomPadding: 8
            }
        }
    }
}
