import SwiftUI

@MainActor
struct SettingsView: View {
    @ObservedObject private var session: AppSession
    @State private var displayName: String
    @State private var isEditingName = false

    init(session: AppSession) {
        self.session = session
        _displayName = State(initialValue: KeychainStore.peerName ?? "")
    }

    init() {
        self.init(session: AppSession.shared)
    }

    var body: some View {
        Form {
            Section("Profile") {
                LabeledContent("Display name") {
                    if isEditingName {
                        TextField("Display name", text: $displayName)
                            .frame(maxWidth: 180)
                    } else {
                        Text(displayName.isEmpty ? "Not set" : displayName)
                            .foregroundStyle(displayName.isEmpty ? .secondary : .primary)
                    }
                }

                Button(isEditingName ? "Save" : "Edit") {
                    if isEditingName {
                        saveDisplayName()
                    }
                    isEditingName.toggle()
                }
            }

            Section("Connection") {
                LabeledContent("Status") {
                    Text(connectionStatus)
                        .foregroundStyle(connectionColor)
                }

                Button("Unpair", role: .destructive) {
                    session.unpair()
                }
                .disabled(isUnpaired)
            }

            Section("About") {
                LabeledContent("Version") {
                    Text(appVersion)
                }
            }

            Section {
                Button("Quit Fchati", role: .destructive) {
                    NSApplication.shared.terminate(nil)
                }
            }
        }
        .formStyle(.grouped)
        .padding()
    }

    private var connectionStatus: String {
        switch session.state {
        case .unpaired:
            "Not connected"
        case .connecting:
            "Connecting..."
        case .connected(_, let peerName):
            "Connected to \(peerName)"
        case .error(let message):
            message
        }
    }

    private var connectionColor: Color {
        switch session.state {
        case .connected:
            .green
        case .error:
            .red
        case .unpaired, .connecting:
            .secondary
        }
    }

    private var isUnpaired: Bool {
        if case .unpaired = session.state {
            return true
        }

        return false
    }

    private var appVersion: String {
        Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown"
    }

    private func saveDisplayName() {
        let trimmedName = displayName.trimmingCharacters(in: .whitespacesAndNewlines)
        displayName = trimmedName
        KeychainStore.peerName = trimmedName.isEmpty ? nil : trimmedName
    }
}
