import AppKit

final class BanUserSheet: NSViewController {

    var onComplete: ((String?, UInt64) -> Void)?

    private let targetNickname: String
    private let reasonField = NSTextField()
    private let durationPicker = NSSegmentedControl(
        labels: ["1 hour", "24 hours", "7 days", "Permanent"],
        trackingMode: .selectOne,
        target: nil, action: nil
    )

    init(nickname: String) {
        self.targetNickname = nickname
        super.init(nibName: nil, bundle: nil)
    }

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

    override func loadView() {
        view = NSView(frame: NSRect(x: 0, y: 0, width: 360, height: 160))
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        buildUI()
    }

    private func buildUI() {
        let titleLabel = NSTextField(labelWithString: "Ban \(targetNickname)")
        titleLabel.font = .boldSystemFont(ofSize: 13)

        let reasonLabel = NSTextField(labelWithString: "Reason:")
        reasonField.placeholderString = "Ban reason (optional)"
        reasonField.setAccessibilityLabel("Ban reason")

        let durationLabel = NSTextField(labelWithString: "Duration:")
        durationPicker.selectedSegment = 3
        durationPicker.setAccessibilityLabel("Ban duration")

        let cancelButton = NSButton(title: "Cancel", target: self, action: #selector(cancelClicked))
        cancelButton.bezelStyle = .rounded

        let banButton = NSButton(title: "Ban", target: self, action: #selector(banClicked))
        banButton.bezelStyle = .rounded; banButton.keyEquivalent = "\r"
        banButton.setAccessibilityLabel("Confirm ban")

        let buttonRow = NSStackView(views: [NSView(), cancelButton, banButton])
        buttonRow.orientation = .horizontal; buttonRow.spacing = 8

        let grid = NSGridView(views: [
            [reasonLabel, reasonField],
            [durationLabel, durationPicker],
        ])
        grid.rowSpacing = 8; grid.columnSpacing = 8
        grid.column(at: 0).xPlacement = .trailing

        let stack = NSStackView(views: [titleLabel, grid, buttonRow])
        stack.orientation = .vertical; stack.spacing = 12
        stack.edgeInsets = NSEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
        stack.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stack)
        NSLayoutConstraint.activate([
            stack.topAnchor.constraint(equalTo: view.topAnchor),
            stack.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            stack.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            stack.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ])
    }

    @objc private func banClicked() {
        let reason = reasonField.stringValue.trimmingCharacters(in: .whitespaces)
        let expiresUnixMs = expiryFromSelection()
        dismiss(nil)
        onComplete?(reason.isEmpty ? nil : reason, expiresUnixMs)
    }

    @objc private func cancelClicked() {
        dismiss(nil)
    }

    private func expiryFromSelection() -> UInt64 {
        let nowMs = UInt64(Date().timeIntervalSince1970 * 1000)
        switch durationPicker.selectedSegment {
        case 0: return nowMs + 3_600_000          // 1 hour
        case 1: return nowMs + 86_400_000         // 24 hours
        case 2: return nowMs + 604_800_000        // 7 days
        default: return 0                          // permanent (0 = no expiry)
        }
    }
}
