import AppKit
import CommanderCore

/// Option+A (o File › Cambia attributi): la finestra "Cambia attributi" di TC, con gli attributi del Mac.
/// Le caselle partono col trattino (= lascia com'è): segno = attiva, vuota = togli.
final class AttributesDialog: ModalPanel {
    private let subfolders = NSButton(checkboxWithTitle: "Includi i file nelle sottocartelle", target: nil, action: nil)
    private let locked = NSButton(checkboxWithTitle: "Bloccato (come Sola lettura di Windows)", target: nil, action: nil)
    private let hidden = NSButton(checkboxWithTitle: "Nascosto", target: nil, action: nil)
    private let hiddenExt = NSButton(checkboxWithTitle: "Estensione nascosta (nel Finder)", target: nil, action: nil)
    private var perms: [Int: NSButton] = [:]
    private let setDate = NSButton(checkboxWithTitle: "Data/ora di modifica:", target: nil, action: nil)
    private let date = NSDatePicker()
    private let time = NSDatePicker()
    private let activeItem: URL?
    private let otherItem: URL?

    /// `active`/`other`: il file sotto il cursore nei due pannelli, per "Carica dal file selezionato".
    static func run(items: [FileItem], active: URL?, other: URL?) -> AttributeChange? {
        let d = AttributesDialog(items: items, active: active, other: other)
        let r = d.runModal { [weak d] e in d?.handleKey(e) ?? false }
        return r == .OK ? d.read() : nil
    }

    private init(items: [FileItem], active: URL?, other: URL?) {
        activeItem = active
        otherItem = other
        super.init(width: 460)
        panel.title = "Cambia attributi: " + (items.count == 1 ? items[0].name : "\(items.count) elementi")
        subfolders.isEnabled = items.contains { $0.showsAsFolder }

        for b in [locked, hidden, hiddenExt] {
            b.allowsMixedState = true
            b.state = .mixed
        }
        let legend = NSTextField(labelWithString: "Trattino = lascia com'è, segno = attiva, vuota = togli.")
        legend.font = .systemFont(ofSize: 11)
        legend.textColor = .secondaryLabelColor

        // Permessi: righe Proprietario, Gruppo, Altri; colonne Lettura, Scrittura, Esecuzione.
        var rows: [[NSView]] = [[NSView(), header("Lettura"), header("Scrittura"), header("Esecuzione")]]
        for (who, shift) in [("Proprietario", 6), ("Gruppo", 3), ("Altri", 0)] {
            var row: [NSView] = [NSTextField(labelWithString: who)]
            for bit in [4, 2, 1] {
                let b = NSButton(checkboxWithTitle: "", target: nil, action: nil)
                b.allowsMixedState = true
                b.state = .mixed
                perms[bit << shift] = b
                row.append(b)
            }
            rows.append(row)
        }
        let grid = NSGridView(views: rows)
        grid.columnSpacing = 18
        grid.rowSpacing = 4
        for i in 1...3 { grid.column(at: i).xPlacement = .center }

        for p in [date, time] {
            p.datePickerStyle = .textFieldAndStepper
            p.locale = Locale(identifier: "it_IT")
            p.dateValue = Date()
            p.isEnabled = false
        }
        date.datePickerElements = .yearMonthDay
        time.datePickerElements = .hourMinuteSecond
        setDate.target = self
        setDate.action = #selector(dateToggled)
        let now = button("Attuale", underline: "t") { [weak self] in self?.setNow() }
        let dateRow = NSStackView(views: [date, time, now])

        let fromActive = button("Dal pannello attivo (1)", underline: "1") { [weak self] in self?.load(self?.activeItem) }
        let fromOther = button("Dall'altro pannello (2)", underline: "2") { [weak self] in self?.load(self?.otherItem) }
        fromActive.isEnabled = active != nil
        fromOther.isEnabled = other != nil
        let loadRow = NSStackView(views: [fromActive, fromOther])
        loadRow.distribution = .fillEqually

        let ok = button("OK", key: "\r") { [weak self] in self?.finish(.OK) }
        let cancel = button("Annulla", key: "\u{1b}") { [weak self] in self?.finish(.cancel) }
        let buttons = NSStackView(views: [NSView(), cancel, ok])

        panel.contentView = column([
            subfolders,
            title("Cambia attributi"), locked, hidden, hiddenExt, legend,
            title("Permessi"), grid,
            setDate, dateRow,
            title("Carica dal file selezionato"), loadRow,
            buttons,
        ], width: 460, spacing: 8)
        panel.initialFirstResponder = locked
    }

    private func header(_ s: String) -> NSTextField {
        let t = NSTextField(labelWithString: s)
        t.font = .systemFont(ofSize: 11)
        t.textColor = .secondaryLabelColor
        return t
    }

    private func title(_ s: String) -> NSTextField {
        let t = NSTextField(labelWithString: s)
        t.font = .boldSystemFont(ofSize: 12)
        return t
    }

    @objc private func dateToggled() {
        date.isEnabled = setDate.state == .on
        time.isEnabled = setDate.state == .on
    }

    private func setNow() {
        setDate.state = .on
        dateToggled()
        date.dateValue = Date()
        time.dateValue = Date()
    }

    /// Mette nella finestra gli attributi e la data del file scelto.
    private func load(_ url: URL?) {
        guard let url else { NSSound.beep(); return }
        let a = AttributeChange.read(url)
        locked.state = a.locked == true ? .on : .off
        hidden.state = a.hidden == true ? .on : .off
        hiddenExt.state = a.hiddenExtension == true ? .on : .off
        for (bit, b) in perms { b.state = a.permissions[bit] == true ? .on : .off }
        if let m = a.modified {
            setDate.state = .on
            dateToggled()
            date.dateValue = m
            time.dateValue = m
        }
    }

    private func read() -> AttributeChange {
        func tri(_ b: NSButton) -> Bool? { b.state == .mixed ? nil : b.state == .on }
        var c = AttributeChange()
        c.includeSubfolders = subfolders.isEnabled && subfolders.state == .on
        c.locked = tri(locked)
        c.hidden = tri(hidden)
        c.hiddenExtension = tri(hiddenExt)
        for (bit, b) in perms { if let v = tri(b) { c.permissions[bit] = v } }
        if setDate.state == .on {
            let cal = Calendar.current
            let d = cal.dateComponents([.year, .month, .day], from: date.dateValue)
            let t = cal.dateComponents([.hour, .minute, .second], from: time.dateValue)
            c.modified = cal.date(from: DateComponents(year: d.year, month: d.month, day: d.day,
                                                       hour: t.hour, minute: t.minute, second: t.second))
        }
        return c
    }

    private func handleKey(_ e: NSEvent) -> Bool {
        let mods = e.modifierFlags.intersection([.control, .option, .command, .shift])
        guard mods == .option, let ch = e.charactersIgnoringModifiers?.lowercased() else { return false }
        switch ch {
        case "1": load(activeItem)
        case "2": load(otherItem)
        case "t": setNow()
        default: return false
        }
        return true
    }
}
