import SwiftUI

struct AuthorizeDeviceView: View {
    var appState: AppState
    @State private var code = ""
    @State private var isAuthorizing = false
    @State private var statusMessage: String?
    @State private var isError = false
    @State private var isDone = false
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(spacing: 24) {
                    Image(systemName: "iphone.badge.checkmark")
                        .font(.system(size: 48))
                        .foregroundStyle(.blue)

                    Text("Authorize New Device")
                        .font(.title2.bold())

                    Text("Enter the 8-digit pairing code shown on the new device.")
                        .font(.subheadline)
                        .foregroundStyle(.secondary)
                        .multilineTextAlignment(.center)

                    TextField("Pairing Code", text: $code)
                        .font(.system(size: 24, weight: .bold, design: .monospaced))
                        .multilineTextAlignment(.center)
                        .keyboardType(.numberPad)
                        .textFieldStyle(.roundedBorder)

                    Button("Authorize") {
                        Task { await authorize() }
                    }
                    .buttonStyle(.borderedProminent)
                    .disabled(code.count < 8 || isAuthorizing || isDone)

                    if isAuthorizing {
                        ProgressView("Preparing history & sending keys...")
                    }

                    if let status = statusMessage {
                        Text(status)
                            .font(.caption)
                            .foregroundStyle(isError ? .red : .green)
                            .multilineTextAlignment(.center)
                    }

                    if isDone {
                        Button("Done") { dismiss() }
                            .buttonStyle(.bordered)
                    }
                }
                .padding(32)
            }
            .navigationTitle("Authorize Device")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    Button("Cancel") { dismiss() }
                }
            }
        }
    }

    private func authorize() async {
        isAuthorizing = true
        isError = false
        statusMessage = nil

        let (success, msg) = await appState.chatClient.authorizeDevice(code: code)
        isAuthorizing = false

        statusMessage = msg
        isError = !success
        if success {
            isDone = true
        }
    }
}
