import SwiftUI
import CoreImage.CIFilterBuiltins
import NucleicCore

/// Settings section to run the iPhone sync server and pair devices (UX_IOS §7, host side).
/// Toggling on starts the LAN listener; "Add iPhone" shows the pairing QR the phone scans.
struct RemoteAccessSection: View {
    @Environment(AppStore.self) private var store
    @State private var showPairing = false

    var body: some View {
        Section("iPhone remote access") {
            Toggle("Allow iPhone to monitor and approve", isOn: Binding(
                get: { store.syncRunning },
                set: { on in Task { on ? await store.startSyncServer() : await store.stopSyncServer() } }
            ))

            if store.syncRunning {
                Button {
                    showPairing = true
                    Task { await store.beginPairing() }
                } label: {
                    Label("Add iPhone…", systemImage: "qrcode")
                }

                if store.pairedDevices.isEmpty {
                    Text("No paired devices yet.")
                        .font(.caption).foregroundStyle(.secondary)
                } else {
                    ForEach(store.pairedDevices, id: \.deviceID) { device in
                        HStack {
                            Label(device.label, systemImage: "iphone")
                            Spacer()
                            Button("Revoke") { Task { await store.revokeDevice(device.deviceID) } }
                                .buttonStyle(.borderless)
                                .foregroundStyle(.red)
                        }
                        .font(.callout)
                    }
                }
            }

            Text("Code and transcripts are end-to-end encrypted (Noise). Pair over the same Wi‑Fi.")
                .font(.caption).foregroundStyle(.secondary)
                .fixedSize(horizontal: false, vertical: true)
        }
        .sheet(isPresented: $showPairing, onDismiss: { Task { await store.endPairing() } }) {
            PairingQRSheet()
        }
    }
}

/// Renders the active pairing QR (`store.pairingQR`) for the phone to scan.
struct PairingQRSheet: View {
    @Environment(AppStore.self) private var store
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        VStack(spacing: 16) {
            Text("Scan with your iPhone").font(.headline)
            if let qr = store.pairingQR, let image = Self.qrImage(qr) {
                Image(nsImage: image)
                    .interpolation(.none)
                    .resizable()
                    .frame(width: 240, height: 240)
                    .background(.white)
                    .padding(8)
                    .background(.white, in: RoundedRectangle(cornerRadius: 12))
            } else {
                ProgressView().frame(width: 240, height: 240)
            }
            Text("Open Nucleic Remote on your iPhone ▸ Pair, and point it here.")
                .font(.caption).foregroundStyle(.secondary)
                .multilineTextAlignment(.center)
            Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
        }
        .padding(24)
        .frame(width: 320)
    }

    private static func qrImage(_ string: String) -> NSImage? {
        let filter = CIFilter.qrCodeGenerator()
        filter.message = Data(string.utf8)
        filter.correctionLevel = "M"
        guard let output = filter.outputImage else { return nil }
        let scaled = output.transformed(by: CGAffineTransform(scaleX: 10, y: 10))
        let context = CIContext()
        guard let cg = context.createCGImage(scaled, from: scaled.extent) else { return nil }
        return NSImage(cgImage: cg, size: NSSize(width: scaled.extent.width, height: scaled.extent.height))
    }
}
