import QtQuick
import QtQuick.Controls
import QtQuick.Dialogs
import QtQuick.Layouts
import QtQuick.Controls.impl
import ISC
import ".."

ColumnLayout {
    id: root
    spacing: 6

    property string exportSummary: ""
    property string importSummary: ""

    // Set by HomePage.qml — a separate .qml file has its own id scope, so
    // dataTabLoader/root from HomePage aren't reachable here directly.
    property int selectedTabIndex: 0
    property var dataTab: null

    Connections {
        target: batchExportController
        function onExportFinished(summary) {
            root.exportSummary = summary
            exportBannerHideTimer.restart()
        }
    }

    Connections {
        target: file_browser
        function onImportFinished(path, message) {
            root.importSummary = message
            importBannerHideTimer.restart()
            if (path !== "")
                streamController.loadFile(path)
        }
    }

    Timer {
        id: exportBannerHideTimer
        interval: 5000
        onTriggered: root.exportSummary = ""
    }

    Timer {
        id: importBannerHideTimer
        interval: 5000
        onTriggered: root.importSummary = ""
    }

    // ── Section label & Refresh ───────────────────────────────────────────
    RowLayout {
        Layout.fillWidth: true
        spacing: 4

        Label {
            text: "SOURCE"
            color: Theme.sideMutedText
            font.family: Theme.uiFontFamily
            font.pixelSize: Theme.fontSm
            font.letterSpacing: 1.5
            font.bold: true
            topPadding: 6
            bottomPadding: 8
            Layout.fillWidth: true
            Layout.alignment: Qt.AlignVCenter
        }

        Button {
            id: refreshBtn
            implicitWidth: 28
            implicitHeight: 28
            hoverEnabled: true
            background: Rectangle {
                color: refreshBtn.pressed ? Theme.buttonPressed : refreshBtn.hovered ? Theme.buttonNeutralHover : "transparent"
                radius: Theme.radiusSm
            }
            contentItem: IconImage {
                source: "../icons/refresh.svg"
                sourceSize.width: 16
                sourceSize.height: 16
                color: Theme.bodyColor
            }
            onClicked: file_browser.refreshFiles()

            AppToolTip {
                visible: refreshBtn.hovered
                text: "Refresh"
            }
        }

        Button {
            id: editBtn
            implicitWidth: 28
            implicitHeight: 28
            hoverEnabled: true
            background: Rectangle {
                color: editBtn.pressed ? Theme.buttonPressed : editBtn.hovered ? Theme.buttonNeutralHover : "transparent"
                radius: Theme.radiusSm
            }
            contentItem: IconImage {
                source: "../icons/edit.svg"
                sourceSize.width: 16
                sourceSize.height: 16
                color: Theme.bodyColor
            }
            onClicked: {
                file_browser.refreshFiles();
                csvEditorDialog.open();
            }

            AppToolTip {
                visible: editBtn.hovered
                text: "Edit"
            }
        }

        Button {
            id: importBtn
            implicitWidth: 28
            implicitHeight: 28
            hoverEnabled: true
            background: Rectangle {
                color: importBtn.pressed ? Theme.buttonPressed : importBtn.hovered ? Theme.buttonNeutralHover : "transparent"
                radius: Theme.radiusSm
            }
            contentItem: IconImage {
                source: "../icons/import.svg"
                sourceSize.width: 16
                sourceSize.height: 16
                color: Theme.bodyColor
            }
            onClicked: importFileDialog.open()

            AppToolTip {
                visible: importBtn.hovered
                text: "Import Data — bring in a raw Z-wafer export CSV"
            }
        }

        Item { implicitWidth: 8 }

        Button {
            id: batchExportBtn
            implicitWidth: 28
            implicitHeight: 28
            hoverEnabled: true
            enabled: file_browser.files.length > 0 && !batchExportController.busy
            opacity: enabled ? 1.0 : 0.4
            background: Rectangle {
                color: batchExportBtn.pressed ? Theme.buttonPressed : batchExportBtn.hovered ? Theme.buttonNeutralHover : "transparent"
                radius: Theme.radiusSm
            }
            contentItem: IconImage {
                source: "../icons/images.svg"
                sourceSize.width: 16
                sourceSize.height: 16
                color: Theme.bodyColor
            }
            onClicked: batchExportDirDialog.open()

            AppToolTip {
                visible: batchExportBtn.hovered && batchExportBtn.enabled
                text: "Batch Export — render every listed file's wafer map to a PNG in select folder"
            }

            AppToolTip {
                visible: batchExportBtn.hovered && !batchExportBtn.enabled
                text: batchExportController.busy
                    ? "Export already in progress…"
                    : "No files to export — load a folder with CSV files first"
            }
        }
    }

    // ── Batch export progress / summary banner ──────────────────────────────
    Rectangle {
        visible: batchExportController.busy || root.exportSummary !== ""
        Layout.fillWidth: true
        height: exportBannerRow.implicitHeight + 12
        radius: Theme.radiusSm
        color: Theme.cardBackground
        border.color: Theme.statusWarningColor
        border.width: 1

        RowLayout {
            id: exportBannerRow
            anchors.fill: parent
            anchors.margins: 6
            spacing: 6

            Label {
                text: batchExportController.busy ? "Exporting wafer maps…" : root.exportSummary
                color: Theme.statusWarningColor
                font.pixelSize: Theme.fontSm
                wrapMode: Text.WordWrap
                Layout.fillWidth: true
            }

            Button {
                visible: !batchExportController.busy
                flat: true
                implicitWidth: 20
                implicitHeight: 20
                onClicked: root.exportSummary = ""
                background: Rectangle { color: "transparent" }
                contentItem: Label {
                    text: "✕"
                    color: Theme.statusWarningColor
                    font.pixelSize: Theme.fontXs
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                }
            }
        }
    }

    // ── Import summary banner ─────────────────────────────────────────────
    Rectangle {
        visible: root.importSummary !== ""
        Layout.fillWidth: true
        height: importBannerRow.implicitHeight + 12
        radius: Theme.radiusSm
        color: Theme.cardBackground
        border.color: Theme.statusWarningColor
        border.width: 1

        RowLayout {
            id: importBannerRow
            anchors.fill: parent
            anchors.margins: 6
            spacing: 6

            Label {
                text: root.importSummary
                color: Theme.statusWarningColor
                font.pixelSize: Theme.fontSm
                wrapMode: Text.WordWrap
                Layout.fillWidth: true
            }

            Button {
                flat: true
                implicitWidth: 20
                implicitHeight: 20
                onClicked: root.importSummary = ""
                background: Rectangle { color: "transparent" }
                contentItem: Label {
                    text: "✕"
                    color: Theme.statusWarningColor
                    font.pixelSize: Theme.fontXs
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                }
            }
        }
    }

    FileDialog {
        id: importFileDialog
        title: "Select Data File To Import"
        nameFilters: ["CSV files (*.csv)"]
        onAccepted: file_browser.importZWaferCsv(String(selectedFile))
    }

    FolderDialog {
        id: batchExportDirDialog
        title: "Export Wafer Maps To…"
        onAccepted: {
            var dir = String(selectedFolder);
            var paths = file_browser.files.map(function(row) { return row.fileName; });
            batchExportController.start(paths, dir);
        }
    }

    // ── Directory button ──────────────────────────────────────────────────
    Button {
        id: dirBtn
        Layout.fillWidth: true
        hoverEnabled: true
        implicitHeight: 36
        leftPadding: 8
        rightPadding: 8
        background: Rectangle {
            radius: Theme.radiusSm
            color: dirBtn.pressed ? Theme.buttonNeutralPressed : dirBtn.hovered ? Theme.buttonNeutralHover : Theme.buttonNeutralBackground
            border.width: Theme.borderThin
            border.color: Theme.fieldBorder
        }
        contentItem: RowLayout {
            spacing: 6
            IconImage {
                source: "../icons/folder.svg"
                width: 14; height: 14
                sourceSize.width: 14
                sourceSize.height: 14
                color: Theme.bodyColor
            }
            Label {
                text: file_browser.currentDirectory.split("/").pop() || file_browser.currentDirectory
                color: Theme.headingColor
                font.pixelSize: Theme.fontSm
                elide: Text.ElideMiddle
                Layout.fillWidth: true
            }
        }
        onClicked: file_browser.chooseDirectory()
    }

    // ── Filter ────────────────────────────────────────────────────────────
    TextField {
        id: filter
        Layout.fillWidth: true
        placeholderText: "Filter…"
        font.pixelSize: Theme.fontSm
        color: Theme.fieldText
        placeholderTextColor: Theme.fieldPlaceholder
        selectedTextColor: Theme.fieldBackground
        selectionColor: Theme.fieldText
        background: Rectangle {
            radius: Theme.radiusXs
            color: Theme.fieldBackground
            border.width: filter.activeFocus ? Theme.borderStrong : Theme.borderThin
            border.color: filter.activeFocus ? Theme.fieldBorderFocus : Theme.fieldBorder
            Behavior on color {
                ColorAnimation { duration: Theme.durationFast }
            }
            Behavior on border.color {
                ColorAnimation { duration: Theme.durationFast }
            }
        }
    }

    // ── File list ─────────────────────────────────────────────────────────
    ListView {
        id: fileList
        Layout.fillWidth: true
        Layout.fillHeight: true
        clip: true
        spacing: 2
        highlight: null
        highlightFollowsCurrentItem: false

        model: file_browser.files

        delegate: ItemDelegate {
            id: fileItem
            width: ListView.view.width
            padding: 8
            highlighted: false
            focusPolicy: Qt.NoFocus

            readonly property bool matchesFilter: {
                if (filter.text === "")
                    return true;
                var q = filter.text.toLowerCase();
                return (modelData.baseName + modelData.waferType + modelData.date).toLowerCase().indexOf(q) >= 0;
            }

            readonly property var dataTab: root.selectedTabIndex === 1 ? root.dataTab : null

            // Run A's effective file: the master file when "Compare vs Master
            // File" is toggled on, otherwise the manually selected file.
            readonly property string effectiveRunAFile: fileItem.dataTab
                ? (fileItem.dataTab.useMasterFile ? fileItem.dataTab.masterFileForRunB : fileItem.dataTab.compareFileA)
                : ""
            readonly property bool isRunA: fileItem.dataTab !== null
                && fileItem.effectiveRunAFile !== "" && modelData.fileName === fileItem.effectiveRunAFile
            readonly property bool isRunB: fileItem.dataTab !== null
                && modelData.fileName === fileItem.dataTab.compareFileB

            // Active highlight logic: on Data tab, highlight the Run A/Run B files (or the
            // resolved master file standing in for Run A); otherwise highlight loadedFile (Map tab).
            readonly property bool isActive: fileItem.dataTab !== null
                ? (fileItem.isRunA || fileItem.isRunB)
                : (streamController.mode === "review" && streamController.loadedFile !== "" && modelData.fileName === streamController.loadedFile)

            // A file registered as any family's master in Settings → Master Files.
            readonly property bool isMasterFile: {
                var m = settingsModel.masters
                for (var fam in m) {
                    if (m[fam] && m[fam] === modelData.fileName) return true
                }
                return false
            }

            readonly property bool isLiveFile: (modelData.baseName || "").toLowerCase().indexOf("live") >= 0
            readonly property bool liveFileBlocked: root.selectedTabIndex === 1 && isLiveFile

            visible: matchesFilter
            height: matchesFilter ? implicitHeight : 0
            enabled: !liveFileBlocked
            opacity: liveFileBlocked ? 0.45 : 1.0
            Behavior on opacity {
                NumberAnimation { duration: Theme.durationFast }
            }

            onClicked: streamController.loadFile(modelData.fileName)

            background: Rectangle {
                color: fileItem.isActive ? Theme.listActiveBackground : fileItem.hovered ? Theme.listHoverBackground : "transparent"
                radius: Theme.radiusSm
                Behavior on color {
                    ColorAnimation { duration: Theme.durationFast }
                }

                // Left accent bar — shown only when active
                Rectangle {
                    visible: fileItem.isActive
                    width: 3
                    radius: 1.5
                    anchors {
                        top: parent.top
                        bottom: parent.bottom
                        left: parent.left
                        topMargin: 5
                        bottomMargin: 5
                    }
                    color: {
                        if (fileItem.isRunA) return Theme.primaryAccent;
                        if (fileItem.isRunB) return Theme.themeSkill;
                        var t = modelData.waferType;
                        if (t === "A" || t === "E" || t === "P")
                            return Theme.familyBlueAccent;
                        if (t === "B" || t === "C" || t === "D")
                            return Theme.familyGreenAccent;
                        if (t === "Z")
                            return Theme.familyVioletAccent;
                        return Theme.headingColor;
                    }
                }
            }

            contentItem: RowLayout {
                spacing: 8

                // Wafer-type avatar (circle)
                Rectangle {
                    implicitWidth: 28
                    implicitHeight: 28
                    Layout.preferredWidth: 28
                    Layout.preferredHeight: 28
                    Layout.alignment: Qt.AlignVCenter
                    radius: 14
                    color: {
                        var t = modelData.waferType;
                        if (t === "A" || t === "E" || t === "P")
                            return Theme.familyBlueFill;
                        if (t === "B" || t === "C" || t === "D")
                            return Theme.familyGreenFill;
                        if (t === "Z")
                            return Theme.familyVioletFill;
                        return Theme.familyNeutralFill;
                    }
                    Label {
                        anchors.centerIn: parent
                        text: modelData.waferType || "?"
                        font.pixelSize: Theme.fontMd
                        font.weight: Font.Bold
                        color: Theme.textOnColor
                    }

                    // Recording indicator dot — distinguishes a live-recorded CSV
                    // (SessionController.startRecording) from a read-memory dump
                    // (DeviceController.parseAndSaveData).
                    Rectangle {
                        visible: modelData.isRecording === true
                        width: 10
                        height: 10
                        radius: 5
                        color: Theme.recordColor
                        border.color: Theme.subtleSectionBackground
                        border.width: 1.5
                        anchors.top: parent.top
                        anchors.right: parent.right
                        anchors.topMargin: -2
                        anchors.rightMargin: -2
                    }

                    // Accent ring — this file is registered as a master (Settings → Master Files).
                    Rectangle {
                        visible: fileItem.isMasterFile
                        anchors.fill: parent
                        radius: parent.radius
                        color: "transparent"
                        border.color: Theme.primaryAccent
                        border.width: 2
                    }
                }

                // Typography hierarchy
                ColumnLayout {
                    spacing: 1
                    Layout.fillWidth: true

                    // Primary: wafer type + serial number, plus a REC badge for recordings
                    RowLayout {
                        Layout.fillWidth: true
                        spacing: 6

                        Label {
                            text: modelData.serialNumber ? (modelData.waferType + modelData.serialNumber) : modelData.baseName
                            color: Theme.headingColor
                            font.pixelSize: Theme.fontMd
                            font.weight: Font.Bold
                            elide: Text.ElideRight
                            Layout.fillWidth: true
                        }

                        Rectangle {
                            visible: modelData.isRecording === true
                            radius: 4
                            color: Qt.alpha(Theme.recordColor, 0.18)
                            implicitWidth: recLabel.implicitWidth + 10
                            implicitHeight: recLabel.implicitHeight + 4
                            Layout.alignment: Qt.AlignVCenter

                            Label {
                                id: recLabel
                                anchors.centerIn: parent
                                text: "REC"
                                color: Theme.recordColor
                                font.pixelSize: Theme.font2xs
                                font.bold: true
                                font.letterSpacing: 0.6
                            }
                        }

                        Rectangle {
                            visible: fileItem.isMasterFile
                            radius: 4
                            color: Qt.alpha(Theme.primaryAccent, 0.18)
                            implicitWidth: masterLabel.implicitWidth + 10
                            implicitHeight: masterLabel.implicitHeight + 4
                            Layout.alignment: Qt.AlignVCenter

                            Label {
                                id: masterLabel
                                anchors.centerIn: parent
                                text: "MASTER"
                                color: Theme.primaryAccent
                                font.pixelSize: Theme.font2xs
                                font.bold: true
                                font.letterSpacing: 0.6
                            }
                        }
                    }

                    // Secondary: date · time
                    RowLayout {
                        spacing: 3
                        Layout.fillWidth: true
                        Label {
                            text: {
                                var d = modelData.date || "";
                                return d.length >= 10 ? d.substring(0, 10) : (d || "—");
                            }
                            color: Theme.bodyColor
                            font.pixelSize: Theme.fontSm
                        }
                        Label {
                            visible: (modelData.timeStr || "") !== ""
                            text: "·"
                            color: Theme.bodyColor
                            font.pixelSize: Theme.fontSm
                            opacity: 0.45
                        }
                        Label {
                            visible: (modelData.timeStr || "") !== ""
                            text: modelData.timeStr || ""
                            color: Theme.bodyColor
                            font.pixelSize: Theme.fontSm
                            opacity: 0.65
                        }
                    }

                    // Tertiary: edited metadata (chamber · notes) if any
                    Label {
                        visible: {
                            var c = modelData.chamber || "";
                            var n = modelData.notes || "";
                            return c !== "" || n !== "";
                        }
                        text: {
                            var parts = [];
                            if (modelData.chamber)
                                parts.push(modelData.chamber);
                            if (modelData.notes)
                                parts.push(modelData.notes);
                            return parts.join("  ·  ");
                        }
                        color: Theme.bodyColor
                        font.pixelSize: Theme.fontXs
                        opacity: 0.7
                        elide: Text.ElideRight
                        Layout.fillWidth: true
                    }
                }
            }
        }
    }

    // ── Footer ────────────────────────────────────────────────────────────
    Label {
        text: file_browser.files.length + " files · CSV only"
        color: Theme.bodyColor
        font.pixelSize: Theme.fontSm
    }

    SelectFileDialog {
        id: csvEditorDialog
        tableModel: file_browser.files
    }
}
