import QtQuick 
import Quickshell
import QtQuick.Controls
import Quickshell.Hyprland
import Quickshell.Io
import Qt.labs.folderlistmodel
import "../../colors"

PanelWindow {
    id: picker
    implicitWidth: screen.width * 0.75
    implicitHeight: screen.height * 0.5
    color: "transparent"
    visible: true
    focusable: true

    FocusScope {
        id: pickerScope
        focus: true

        Keys.onReleased: function(event) {
            if (event.key === Qt.Key_Escape) {
                console.log("Pressed Escape, closing Wallpaper Picker")
                wallpaperLoader.active = false
            }
        }

        Rectangle {
            anchors.fill: parent
            color: "lightblue"
        }
    }

    Rectangle {
        anchors.fill: parent
        radius: 10
        color: Qt.alpha(Colors.surfaceContainerLowest, 0.5)

        border.width: 2
        border.color: Colors.outlineVariant

        clip: true

        TextField {
            id: filterText
            placeholderText: "Search..."
            onTextChanged: wallpaperContainer.filterImages()

            anchors.top: parent.top
            anchors.topMargin: 20
            anchors.horizontalCenter: parent.horizontalCenter

            width: parent.width - 35
            height: 45

            color: "white"
            placeholderTextColor: "#888"

            background: Rectangle {

                radius: 12
                color: filterText.activeFocus ? Colors.tertiary_fg : Colors.primary_fg
                border.color: filterText.activeFocus ? Colors.tertiary : Colors.primary
                border.width: 1
            }

            Keys.onReleased: {
                if (event.key === Qt.Key_Escape) {
                    console.log("Escape pressed inside TextField")
                    console.log("Pressed Escape, closing Wallpaper Picker")
                    // wallpaperLoader.active = false
                    filterText.text = ""
                    filterText.focus = false
                    event.accepted = true
                    pickerScope.focus = true
                }
            }
        }

        
        //Wallpaper space
        Rectangle {
            id: wallpaperContainer

            anchors.horizontalCenter: parent.horizontalCenter
            anchors.bottom: parent.bottom
            anchors.bottomMargin: 20

            width: parent.width - 35
            height: parent.height - 100
            color: Colors.surfaceContainer
            radius: 10

            clip: true


            // get folder url
            FolderListModel {
                id: imagesModel
                folder: "file://" + Quickshell.env("HOME") + "/.cache/wallpaper-thumbs"
                nameFilters: ["*.png", "*.jpg", "*.jpeg"]
                showDirs: false

                onCountChanged: {
                    wallpaperContainer.filterImages()  // ensure filteredModel is filled when folder loads
                }
            }

            ListModel {
                id: filteredModel

            }

            function filterImages(){
                filteredModel.clear()

                for (let i = 0; i < imagesModel.count; ++i) {
                    let name = imagesModel.get(i, "fileName")
                    let path = imagesModel.get(i, "filePath")
                    let url = imagesModel.get(i, "fileUrl")


                    if (name.toLowerCase().startsWith(filterText.text.toLowerCase())) {
                        filteredModel.append({ fileName: name, filePath: path, fileUrl: url })
                    }
                }

            }

            // grid 
            Item {
                anchors.fill: parent
                anchors.margins: 15

                GridView {
                    id: grid
                    anchors.fill: parent
                    cellWidth: parent.width/6
                    cellHeight: parent.height/2 + 15
                    model:filteredModel

                    boundsBehavior: Flickable.StopAtBounds  


                    // pictures + text
                    delegate: Rectangle {
                        width:  grid.cellWidth -10 
                        height: grid.cellHeight -25
                        color: mouseArea.containsMouse ? Qt.alpha(Colors.surfaceContainerHover, 0.5) : "transparent" // select color
                        radius: 10
                        clip: true 

                        Column {
                            spacing: 20

                            Rectangle {
                                width: grid.cellWidth -10 
                                height: grid.cellHeight * 0.7

                                border.width: 2
                                border.color: mouseArea.containsMouse ? Qt.alpha(Colors.surfaceContainerHover, 0.5) : "transparent"

                                radius: 10
                                
                                Image { // Image
                                    source: filePath
                                    anchors.fill: parent
                                    fillMode: Image.PreserveAspectCrop

                                    sourceSize.width: grid.cellWidth -10
                                    sourceSize.height: grid.cellHeight * 0.7

                                    asynchronous: true
                                    cache: true
                                }

                                Rectangle {
                                    anchors.fill: parent
                                    color: "transparent"
                                    border.width: 2
                                    border.color: mouseArea.containsMouse ? Qt.alpha(Colors.surfaceContainerHover, 0.5) : "transparent"
                                }
                            }

                            Rectangle { // highlight of text
                                id: textHighlight
                                width: parent.width - 10
                                height: 24
                                color: mouseArea.containsMouse ? Qt.alpha(Colors.surfaceContainerHover, 0.5) : "transparent"
                                anchors.horizontalCenter: parent.horizontalCenter
                            
                                Text {
                                    text: fileName
                                    elide: Text.ElideRight
                                    width: parent.width
                                    horizontalAlignment: Text.AlignHCenter

                                    font.pixelSize: 15
                                    font.family: "Fira Sans" 
                                    color: Colors.surface_fg
                                }
                            }
                        }
                        Item {
                            anchors.fill: parent
                            Process {
                                id: wallpaperProcess
                                command: ["sh", "-c", Quickshell.env("HOME") + "/.config/quickshell/modules/wp/set-wallpaper.sh" + " " + model.filePath + " &"]
                                stdout: StdioCollector {
                                    onStreamFinished: console.log('line read:', this.text)
                                }
                            }

                            MouseArea {
                                id: mouseArea
                                anchors.fill: parent
                                hoverEnabled: true
                                cursorShape: Qt.PointingHandCursor
                                onClicked: {
                                    console.log("Setting wallpaper to:", model.fileName)
                                    wallpaperProcess.startDetached()
                                    
                                    wLoader.closeWallpaperPicker()
                                }
                            }
                        }
                    }
                    
                    ScrollBar.vertical: ScrollBar { 
                        policy: ScrollBar.AlwaysOn
                    }
                }
            }

            Rectangle { // border of wallpaper container
                id: borderOverlay
                anchors.fill: parent
                radius: 10
                color: "transparent"
                border.color: Colors.primary
                border.width: 1
                z: 999   
            }
        }
    }
}