import AppKit
import CommanderCore

final class MainWindowController: NSWindowController, NSWindowDelegate, FilePanelDelegate {
    let left: FilePanel
    let right: FilePanel
    private(set) var active: FilePanel
    var other: FilePanel { active === left ? right : left }

    let queue = TransferQueue()
    private let transferBar: TransferBar
    private var hotlist: [HotlistEntry] = HotlistStore.load()
    private var menuOpen = false
    private var cutChangeCount: Int?

    private static let textEdit = URL(fileURLWithPath: "/System/Applications/TextEdit.app")

    init() {
        let state = AppState.load()
        left = FilePanel(side: .left, tabs: state.left.makeTabs(), activeTab: state.left.active)
        right = FilePanel(side: .right, tabs: state.right.makeTabs(), activeTab: state.right.active)
        active = state.rightActive ? right : left
        transferBar = TransferBar(queue: queue)

        let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1500, height: 900),
                         styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
        w.title = "Mac Commander"
        w.minSize = NSSize(width: 800, height: 400)
        super.init(window: w)
        w.delegate = self
        buildLayout()
        if !w.setFrameUsingName("Principale") { w.center() }
        w.setFrameAutosaveName("Principale")

        for p in [left, right] {
            p.delegate = self
            if !p.navigate(to: p.tab.url, select: p.tab.cursorName, record: false, quiet: true) {
                p.navigate(to: FileManager.default.homeDirectoryForCurrentUser)
            }
        }
        setActive(active)

        queue.onChange = { [weak self] in self?.transferBar.update() }
        queue.onJobFinished = { [weak self] _ in
            self?.left.refresh()
            self?.right.refresh()
        }
        transferBar.update()
    }

    required init?(coder: NSCoder) { fatalError() }

    private func buildLayout() {
        let split = NSSplitView()
        split.orientation = .horizontal
        split.distribution = .fillEqually
        split.spacing = 1
        split.addArrangedSubview(left)
        split.addArrangedSubview(right)
        split.wantsLayer = true
        split.layer?.backgroundColor = NSColor(white: 0.25, alpha: 1).cgColor

        let keys: [(String, Command)] = [("F3 Visualizza", .view), ("F4 Modifica", .edit), ("F5 Copia", .copy),
                                         ("F6 Sposta", .move), ("F7 Nuova cartella", .mkdir), ("F8 Elimina", .delete),
                                         ("⌥F4 Esci", .quit)]
        let keyBar = NSStackView(views: keys.map { title, cmd in
            let b = ActionButton(title) { [weak self] in self?.perform(cmd) }
            b.bezelStyle = .push
            b.controlSize = .small
            b.font = Theme.small
            return b
        })
        keyBar.orientation = .horizontal
        keyBar.distribution = .fillEqually
        keyBar.spacing = 4
        keyBar.edgeInsets = NSEdgeInsets(top: 3, left: 4, bottom: 4, right: 4)

        let root = NSView()
        for v in [split, transferBar, keyBar] as [NSView] {
            v.translatesAutoresizingMaskIntoConstraints = false
            root.addSubview(v)
            NSLayoutConstraint.activate([
                v.leadingAnchor.constraint(equalTo: root.leadingAnchor),
                v.trailingAnchor.constraint(equalTo: root.trailingAnchor),
            ])
        }
        // La barra della coda sparisce quando è vuota: altezza 0.
        transferHeight = transferBar.heightAnchor.constraint(equalToConstant: 0)
        NSLayoutConstraint.activate([
            split.topAnchor.constraint(equalTo: root.topAnchor),
            transferBar.topAnchor.constraint(equalTo: split.bottomAnchor),
            keyBar.topAnchor.constraint(equalTo: transferBar.bottomAnchor),
            keyBar.bottomAnchor.constraint(equalTo: root.bottomAnchor),
            keyBar.heightAnchor.constraint(equalToConstant: 30),
            transferHeight!,
        ])
        window?.contentView = root
    }

    private var transferHeight: NSLayoutConstraint?

    private func updateTransferBar() {
        transferBar.update()
        transferHeight?.constant = transferBar.isHidden ? 0 : 28
    }

    // MARK: - Pannello attivo

    func setActive(_ p: FilePanel) {
        if active !== p { active.cancelRename() }
        active = p
        left.isActive = p === left
        right.isActive = p === right
        window?.makeFirstResponder(p.table)
    }

    func panelDidBecomeActive(_ panel: FilePanel) {
        if panel !== active { setActive(panel) }
    }

    func panelOpenFile(_ panel: FilePanel, item: FileItem) {
        NSWorkspace.shared.open(item.url)
    }

    func panelShowLocations(_ panel: FilePanel) {
        showLocations(for: panel)
    }

    // MARK: - Tastiera

    /// Tutti i tasti dell'app passano da qui, prima di AppKit.
    func handleKeyEvent(_ e: NSEvent) -> NSEvent? {
        let flags = e.modifierFlags.intersection([.control, .option, .shift, .command])
        if menuOpen { return e }

        // Finestre di dialogo: F2 = Accoda.
        if NSApp.modalWindow != nil {
            if e.keyCode == KeyCode.f2 && flags.isEmpty, let b = Dialogs.queueButton {
                b.performClick(nil)
                return nil
            }
            return textShortcut(e, flags) ? nil : e
        }

        // Campi di testo (rinomina, ricerche): Ctrl+C/X/V/A come su Windows.
        if let tv = NSApp.keyWindow?.firstResponder as? NSTextView, tv.isEditable {
            return textShortcut(e, flags) ? nil : e
        }

        if let viewer = NSApp.keyWindow?.windowController as? ViewerWindowController {
            return viewer.handleKey(e) ? nil : e
        }

        guard let window, NSApp.keyWindow === window, window.attachedSheet == nil else { return e }
        if flags.contains(.command) { return e }

        if let cmd = KeyMap.command(for: e, quickSearchActive: active.quickSearchActive) {
            perform(cmd)
            return nil
        }
        // Ricerca rapida: lettere e cifre senza Ctrl/Option.
        if flags.isDisjoint(with: [.control, .option]), let chars = e.characters, !chars.isEmpty,
           chars.unicodeScalars.allSatisfy({ $0.value >= 0x20 && $0.value != 0x7F && !(0xF700...0xF8FF).contains($0.value) }) {
            active.appendFilter(chars)
            return nil
        }
        return e
    }

    private func textShortcut(_ e: NSEvent, _ flags: NSEvent.ModifierFlags) -> Bool {
        guard flags == .control, let tv = NSApp.keyWindow?.firstResponder as? NSTextView else { return false }
        switch e.charactersIgnoringModifiers?.lowercased() {
        case "c": tv.copy(nil)
        case "x": tv.cut(nil)
        case "v": tv.paste(nil)
        case "a": tv.selectAll(nil)
        case "z": tv.undoManager?.undo()
        default: return false
        }
        return true
    }

    // MARK: - Comandi

    func perform(_ cmd: Command) {
        let p = active
        switch cmd {
        case .up: p.moveCursor(by: -1)
        case .down: p.moveCursor(by: 1)
        case .pageUp: p.moveCursor(by: -p.pageSize)
        case .pageDown: p.moveCursor(by: p.pageSize)
        case .home: p.moveCursor(by: -p.items.count)
        case .end: p.moveCursor(by: p.items.count)
        case .markUp: p.markAndMove(-1)
        case .markDown: p.markAndMove(1)
        case .open: p.open()
        case .parentOrFilterBack: p.backspace()
        case .goParent: p.goParent()
        case .enterPackage: p.enterAnyFolder()
        case .goRoot: p.goRoot()
        case .switchPanel: setActive(other)
        case .escape: p.clearFilter()

        case .transferLeft: transfer(to: left)
        case .transferRight: transfer(to: right)
        case .openInNewTab:
            if let i = p.cursorItem, i.showsAsFolder { p.newTab(url: i.isParent ? p.currentURL.deletingLastPathComponent() : i.url) }
            else { p.newTab() }
        case .openInOtherNewTab:
            let url = p.cursorItem.flatMap { $0.showsAsFolder ? ($0.isParent ? p.currentURL.deletingLastPathComponent() : $0.url) : nil } ?? p.currentURL
            other.newTab(url: url)
        case .historyBack: p.historyMove(-1)
        case .historyForward: p.historyMove(1)
        case .historyList: showHistory()
        case .locationLeft: showLocations(for: left)
        case .locationRight: showLocations(for: right)
        case .hotlist: showHotlist()

        case .newTab: p.newTab()
        case .newTabBackground: p.newTab(activate: false)
        case .closeTab: p.closeTab()
        case .closeAllTabs: p.closeOtherTabs()
        case .nextTab: p.cycleTab(1)
        case .prevTab: p.cycleTab(-1)
        case .tabList: showTabList()
        case .swapPanels:
            let l = left.currentURL, r = right.currentURL
            left.navigate(to: r)
            right.navigate(to: l)
        case .reread: p.refresh()

        case .view:
            if let i = p.cursorItem, !i.showsAsFolder { ViewerWindowController.show(i.url) }
        case .edit:
            if let i = p.cursorItem, !i.showsAsFolder { openInEditor(i.url) }
        case .newTextFile: newTextFile()
        case .copy: copyOrMove(.copy)
        case .move: copyOrMove(.move)
        case .copySameDir: copySameDir()
        case .renameInPlace: p.beginRename()
        case .mkdir: makeDirectory()
        case .delete: delete(permanent: false)
        case .deletePermanent: delete(permanent: true)
        case .calcSize: calcSize()
        case .clipCopy: clipboard(cut: false)
        case .clipCut: clipboard(cut: true)
        case .clipPaste: paste()

        case .space:
            if p.quickSearchActive { p.appendFilter(" ") } else { p.markAndMove(1) }
        case .insertMark: p.markAndMove(1)
        case .selectMask: selectByMask(on: true)
        case .deselectMask: selectByMask(on: false)
        case .invertSelection: p.invertMarks()
        case .restoreSelection: p.restoreSelection()
        case .selectAll: p.setMarks(where: { _ in true }, on: true)
        case .deselectAll: p.setMarks(where: { _ in true }, on: false)
        case .selectSameExt, .deselectSameExt:
            guard let c = p.cursorItem, !c.showsAsFolder else { return }
            let ext = c.ext.lowercased()
            p.setMarks(where: { !$0.showsAsFolder && $0.ext.lowercased() == ext }, on: cmd == .selectSameExt)
        case .quit: NSApp.terminate(nil)
        }
    }

    /// Ctrl+← / Ctrl+→: il pannello verso cui punta la freccia mostra la cartella sotto il cursore
    /// (se il cursore è nell'altro pannello e su una cartella), altrimenti la cartella dell'altro pannello.
    private func transfer(to target: FilePanel) {
        let source = target === left ? right : left
        var url = source.currentURL
        if active === source, let i = source.cursorItem, i.showsAsFolder {
            url = i.isParent ? source.currentURL.deletingLastPathComponent() : i.url
        }
        target.navigate(to: url)
    }

    private func openInEditor(_ url: URL) {
        NSWorkspace.shared.open([url], withApplicationAt: Self.textEdit, configuration: NSWorkspace.OpenConfiguration())
    }

    // MARK: - Copia, sposta, crea, elimina

    private func describe(_ items: [FileItem]) -> String {
        if items.count == 1 { return "\"\(items[0].name)\"" }
        let folders = items.filter(\.showsAsFolder).count
        let files = items.count - folders
        var parts: [String] = []
        if files > 0 { parts.append(files == 1 ? "1 file" : "\(files) file") }
        if folders > 0 { parts.append(folders == 1 ? "1 cartella" : "\(folders) cartelle") }
        return parts.joined(separator: " e ")
    }

    private func copyOrMove(_ kind: TransferKind) {
        let items = active.selectedItems()
        guard !items.isEmpty else { return }
        let verb = kind == .copy ? "Copia" : "Sposta"
        let dest = other.currentURL.path.hasSuffix("/") ? other.currentURL.path : other.currentURL.path + "/"
        let result = Dialogs.prompt("\(verb) \(describe(items)) in:", value: dest, okTitle: "OK", queueTitle: "F2 Accoda")
        let text: String
        switch result {
        case .ok(let t), .queue(let t): text = t
        case .cancel: return
        }
        guard let (dir, name) = parseDestination(text, count: items.count) else { return }
        queue.enqueue(TransferJob(kind: kind, sources: items.map(\.url), destination: dir, newName: name))
        active.clearMarksAfterOperation()
    }

    /// "…/cartella/" o una cartella esistente = destinazione; altrimenti, con un solo elemento, nuovo nome.
    private func parseDestination(_ raw: String, count: Int) -> (URL, String?)? {
        var text = (raw.trimmingCharacters(in: .whitespaces) as NSString).expandingTildeInPath
        guard !text.isEmpty else { return nil }
        if !text.hasPrefix("/") { text = active.currentURL.appendingPathComponent(text).path + (text.hasSuffix("/") ? "/" : "") }
        var isDir: ObjCBool = false
        if text.hasSuffix("/") || (FileManager.default.fileExists(atPath: text, isDirectory: &isDir) && isDir.boolValue) || count > 1 {
            return (URL(fileURLWithPath: text, isDirectory: true), nil)
        }
        let u = URL(fileURLWithPath: text)
        return (u.deletingLastPathComponent(), u.lastPathComponent)
    }

    private func copySameDir() {
        guard let item = active.cursorItem, !item.isParent else { return }
        let base = item.baseName as NSString
        guard case .ok(let name) = Dialogs.prompt("Copia \"\(item.name)\" con il nome:", value: item.name,
                                                  selection: NSRange(location: 0, length: base.length)),
              !name.isEmpty, name != item.name else { return }
        queue.enqueue(TransferJob(kind: .copy, sources: [item.url], destination: active.currentURL, newName: name))
    }

    private func makeDirectory() {
        let suggestion = active.cursorItem.map { $0.isParent ? "" : ($0.showsAsFolder ? $0.name : $0.baseName) } ?? ""
        guard case .ok(let raw) = Dialogs.prompt("Nuova cartella:", value: suggestion) else { return }
        let name = raw.trimmingCharacters(in: .whitespaces)
        guard !name.isEmpty else { return }
        let url = active.currentURL.appendingPathComponent(name)
        do {
            try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
            active.tab.cursorName = name.split(separator: "/").first.map(String.init)
            active.refresh()
        } catch {
            Dialogs.message("Non riesco a creare la cartella", info: error.localizedDescription, style: .warning)
        }
    }

    private func newTextFile() {
        guard case .ok(let raw) = Dialogs.prompt("Nuovo file di testo:", value: "testo.txt",
                                                 selection: NSRange(location: 0, length: 5)) else { return }
        let name = raw.trimmingCharacters(in: .whitespaces)
        guard !name.isEmpty else { return }
        let url = active.currentURL.appendingPathComponent(name)
        if !FileManager.default.fileExists(atPath: url.path) {
            guard FileManager.default.createFile(atPath: url.path, contents: Data()) else {
                Dialogs.message("Non riesco a creare \"\(name)\"", style: .warning)
                return
            }
        }
        active.tab.cursorName = name
        active.refresh()
        openInEditor(url)
    }

    private func delete(permanent: Bool) {
        let items = active.selectedItems()
        guard !items.isEmpty else { return }
        let ok = permanent
            ? Dialogs.confirm("Eliminare definitivamente \(describe(items))?", info: "Non finiscono nel Cestino.", ok: "Elimina")
            : Dialogs.confirm("Spostare nel Cestino \(describe(items))?", ok: "Sposta nel Cestino")
        guard ok else { return }
        // Il cursore va sul primo elemento che resta.
        let gone = Set(items.map(\.url))
        if let next = active.items[active.cursorRow...].first(where: { !gone.contains($0.url) })
            ?? active.items[..<active.cursorRow].last(where: { !gone.contains($0.url) }) {
            active.tab.cursorName = next.name
        }
        queue.enqueue(TransferJob(kind: permanent ? .delete : .trash, sources: items.map(\.url)))
        active.clearMarksAfterOperation()
    }

    private func calcSize() {
        let items = active.selectedItems()
        guard !items.isEmpty else { return }
        var bytes: Int64 = 0, files = 0, folders = 0, remaining = items.count
        for i in items {
            active.computeSize(i.url) { b, f, d in
                bytes += b
                files += f
                folders += d + (i.showsAsFolder ? 1 : 0)
                remaining -= 1
                if remaining == 0 {
                    Dialogs.message("Spazio occupato: \(Format.short(bytes))",
                                    info: "\(Format.bytes(bytes)) byte in \(files) file e \(folders) cartelle")
                }
            }
        }
    }

    // MARK: - Appunti (compatibili col Finder)

    private func clipboard(cut: Bool) {
        let items = active.selectedItems()
        guard !items.isEmpty else { return }
        let pb = NSPasteboard.general
        pb.clearContents()
        pb.writeObjects(items.map { $0.url as NSURL })
        cutChangeCount = cut ? pb.changeCount : nil
    }

    private func paste() {
        let pb = NSPasteboard.general
        guard let urls = pb.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL],
              !urls.isEmpty else { return }
        let move = cutChangeCount == pb.changeCount
        queue.enqueue(TransferJob(kind: move ? .move : .copy, sources: urls, destination: active.currentURL))
        if move { cutChangeCount = nil }
    }

    // MARK: - Selezione con maschera

    private var lastMask = "*.*"

    private func selectByMask(on: Bool) {
        guard case .ok(let mask) = Dialogs.prompt(on ? "Seleziona i file:" : "Deseleziona i file:", value: lastMask),
              !mask.isEmpty else { return }
        lastMask = mask
        active.setMarks(where: { Matcher.matches($0.name, mask: mask) }, on: on)
    }

    // MARK: - Menu: preferiti, posizioni, cronologia, schede

    private func popUp(_ menu: NSMenu, in panel: FilePanel, at anchor: NSView? = nil) {
        menuOpen = true
        defer { menuOpen = false }
        if let anchor {
            menu.popUp(positioning: nil, at: NSPoint(x: 0, y: anchor.bounds.maxY + 4), in: anchor)
            return
        }
        let row = max(panel.cursorRow, 0)
        let r = panel.table.rect(ofRow: row)
        menu.popUp(positioning: nil, at: NSPoint(x: r.minX + 30, y: r.maxY), in: panel.table)
    }

    private func showHotlist() {
        let menu = NSMenu()
        menu.autoenablesItems = false
        addHotlist(hotlist, to: menu)
        menu.addItem(.separator())
        let here = active.currentURL
        menu.addItem(ActionMenuItem("Aggiungi «\(here.lastPathComponent)» ai preferiti…") { [weak self] in self?.addToHotlist(here) })
        menu.addItem(ActionMenuItem("Modifica i preferiti…") { [weak self] in self?.editHotlist() })
        popUp(menu, in: active)
    }

    private func addHotlist(_ entries: [HotlistEntry], to menu: NSMenu) {
        for e in entries {
            if e.isSeparator { menu.addItem(.separator()); continue }
            if let items = e.items {
                let item = NSMenuItem(title: e.title, action: nil, keyEquivalent: "")
                let sub = NSMenu()
                addHotlist(items, to: sub)
                item.submenu = sub
                menu.addItem(item)
                continue
            }
            guard let url = e.url else { continue }
            let item = ActionMenuItem(e.title, key: e.accessKey ?? "") { [weak self] in
                guard let self else { return }
                self.active.navigate(to: url)
            }
            item.toolTip = Format.path(url)
            menu.addItem(item)
        }
    }

    private func addToHotlist(_ url: URL) {
        guard case .ok(let name) = Dialogs.prompt("Nome del preferito:", info: Format.path(url), value: url.lastPathComponent),
              !name.isEmpty else { return }
        hotlist.append(HotlistEntry(name: name, path: HotlistStore.storedPath(url)))
        do { try HotlistStore.save(hotlist) } catch {
            Dialogs.message("Non riesco a salvare i preferiti", info: error.localizedDescription, style: .warning)
        }
    }

    private func editHotlist() {
        let file = HotlistStore.defaultURL
        if !FileManager.default.fileExists(atPath: file.path) { try? HotlistStore.save(hotlist) }
        openInEditor(file)
    }

    func reloadHotlist() { hotlist = HotlistStore.load() }

    private func showLocations(for panel: FilePanel) {
        setActive(panel)
        let menu = NSMenu()
        let home = FileManager.default.homeDirectoryForCurrentUser
        let places: [(String, URL)] = [
            ("Home", home),
            ("Scrivania", home.appendingPathComponent("Desktop")),
            ("Download", home.appendingPathComponent("Downloads")),
            ("Documenti", home.appendingPathComponent("Documents")),
            ("iCloud Drive", home.appendingPathComponent("Library/Mobile Documents/com~apple~CloudDocs")),
            ("Applicazioni", URL(fileURLWithPath: "/Applications")),
        ]
        for (title, url) in places where FileManager.default.fileExists(atPath: url.path) {
            menu.addItem(ActionMenuItem(title) { panel.navigate(to: url) })
        }
        menu.addItem(.separator())
        let vols = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: [.volumeLocalizedNameKey],
                                                         options: [.skipHiddenVolumes]) ?? []
        for v in vols {
            let name = (try? v.resourceValues(forKeys: [.volumeLocalizedNameKey]))?.volumeLocalizedName ?? v.lastPathComponent
            let item = ActionMenuItem(v.path == "/" ? "\(name)  /" : "\(name)  \(Format.path(v))") { panel.navigate(to: v) }
            item.image = NSWorkspace.shared.icon(forFile: v.path)
            item.image?.size = NSSize(width: 16, height: 16)
            menu.addItem(item)
        }
        popUp(menu, in: panel, at: panel.locationAnchor)
    }

    private func showHistory() {
        let p = active
        let menu = NSMenu()
        for (i, u) in p.tab.history.enumerated().reversed() {
            let item = ActionMenuItem(Format.path(u)) { p.historyJump(i) }
            item.state = i == p.tab.historyIndex ? .on : .off
            menu.addItem(item)
        }
        popUp(menu, in: p)
    }

    private func showTabList() {
        let p = active
        let menu = NSMenu()
        for (i, t) in p.tabs.enumerated() {
            let item = ActionMenuItem(Format.path(t.url)) { p.switchTab(i) }
            item.state = i == p.activeTabIndex ? .on : .off
            menu.addItem(item)
        }
        popUp(menu, in: p)
    }

    // MARK: - Stato

    func saveState() {
        AppState(left: PanelState(left), right: PanelState(right), rightActive: active === right).save()
    }

    func windowWillClose(_ notification: Notification) { saveState() }
}

// MARK: - Stato salvato tra un avvio e l'altro

struct PanelState: Codable {
    var tabs: [String]
    var sorts: [FileSort]
    var active: Int

    init(tabs: [String], active: Int) {
        self.tabs = tabs
        self.sorts = tabs.map { _ in FileSort() }
        self.active = active
    }

    init(_ p: FilePanel) {
        tabs = p.tabs.map(\.url.path)
        sorts = p.tabs.map(\.sort)
        active = p.activeTabIndex
    }

    func makeTabs() -> [PanelTab] {
        tabs.enumerated().map { i, path in
            PanelTab(url: URL(fileURLWithPath: path, isDirectory: true), sort: sorts.indices.contains(i) ? sorts[i] : FileSort())
        }
    }
}

struct AppState: Codable {
    var left: PanelState
    var right: PanelState
    var rightActive: Bool

    private static let key = "statoPannelli"

    static func load() -> AppState {
        if let data = UserDefaults.standard.data(forKey: key), let s = try? JSONDecoder().decode(AppState.self, from: data) {
            return s
        }
        // Primo avvio: le cartelle che TC aveva aperto (D:\ era la "home" del NAS).
        let home = FileManager.default.homeDirectoryForCurrentUser
        func first(_ paths: [String]) -> String {
            paths.map { ($0 as NSString).expandingTildeInPath }.first { FileManager.default.fileExists(atPath: $0) } ?? home.path
        }
        return AppState(left: PanelState(tabs: [first(["~/Server/home/Downloads", "~/Downloads"])], active: 0),
                        right: PanelState(tabs: [first(["~/Server/home/Downloads/- FILM", "~/Downloads"])], active: 0),
                        rightActive: false)
    }

    func save() {
        if let data = try? JSONEncoder().encode(self) { UserDefaults.standard.set(data, forKey: Self.key) }
    }
}
