import SwiftUI

struct EditServerView: View {
    @Environment(\.dismiss) private var dismiss
    @Environment(ServerProfileStore.self) private var profileStore

    let profile: ServerProfile

    @State private var name: String
    @State private var serverURL: String
    @State private var tokenId: String = ""
    @State private var tokenSecret: String = ""
    @State private var showTokenId = false
    @State private var showTokenSecret = false
    @State private var changeCredentials = false
    @State private var isSaving = false
    @State private var saveError: String? = nil

    init(profile: ServerProfile) {
        self.profile = profile
        _name = State(initialValue: profile.name)
        _serverURL = State(initialValue: profile.serverURL)
    }

    var body: some View {
        NavigationStack {
            Form {
                // Name & URL
                Section(L("onboarding.server.name.label")) {
                    TextField(L("onboarding.server.name.placeholder"), text: $name)
                        .autocorrectionDisabled()
                        .textInputAutocapitalization(.words)
                }

                Section(L("onboarding.server.title")) {
                    TextField(L("onboarding.server.placeholder"), text: $serverURL)
                        .keyboardType(.URL)
                        .autocorrectionDisabled()
                        .textInputAutocapitalization(.never)
                        .textContentType(.URL)
                }

                // Optional credential rotation
                Section {
                    Toggle(L("settings.servers.edit.changecreds"), isOn: $changeCredentials.animation())
                } footer: {
                    Text(L("settings.servers.edit.changecreds.footer"))
                        .font(.footnote)
                }

                if changeCredentials {
                    Section(L("onboarding.token.id.label")) {
                        HStack {
                            Group {
                                if showTokenId {
                                    TextField(L("onboarding.token.id.label"), text: $tokenId)
                                } else {
                                    SecureField(L("onboarding.token.id.label"), text: $tokenId)
                                }
                            }
                            .autocorrectionDisabled()
                            .textInputAutocapitalization(.never)
                            .textContentType(.username)

                            Button { showTokenId.toggle() } label: {
                                Image(systemName: showTokenId ? "eye.slash" : "eye")
                                    .foregroundStyle(.secondary)
                            }
                            .buttonStyle(.plain)
                        }
                    }

                    Section(L("onboarding.token.secret.label")) {
                        HStack {
                            Group {
                                if showTokenSecret {
                                    TextField(L("onboarding.token.secret.label"), text: $tokenSecret)
                                } else {
                                    SecureField(L("onboarding.token.secret.label"), text: $tokenSecret)
                                }
                            }
                            .autocorrectionDisabled()
                            .textInputAutocapitalization(.never)
                            .textContentType(.password)

                            Button { showTokenSecret.toggle() } label: {
                                Image(systemName: showTokenSecret ? "eye.slash" : "eye")
                                    .foregroundStyle(.secondary)
                            }
                            .buttonStyle(.plain)
                        }
                    }
                }

                if let error = saveError {
                    Section {
                        Label(error, systemImage: "exclamationmark.circle.fill")
                            .foregroundStyle(.red)
                            .font(.footnote)
                    }
                }
            }
            .navigationTitle(L("settings.servers.edit.title"))
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button(L("create.cancel")) { dismiss() }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button(L("common.done")) {
                        save()
                    }
                    .disabled(!canSave || isSaving)
                    .overlay { if isSaving { ProgressView().scaleEffect(0.7) } }
                }
            }
        }
    }

    // MARK: - Helpers

    private var canSave: Bool {
        !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty &&
        !serverURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty &&
        (!changeCredentials || (!tokenId.isEmpty && !tokenSecret.isEmpty))
    }

    private func save() {
        isSaving = true
        saveError = nil

        var cleanURL = serverURL.trimmingCharacters(in: .whitespacesAndNewlines)
        if !cleanURL.hasPrefix("http://") && !cleanURL.hasPrefix("https://") {
            cleanURL = "https://" + cleanURL
        }
        while cleanURL.hasSuffix("/") { cleanURL = String(cleanURL.dropLast()) }

        profileStore.updateProfile(
            profile,
            newName: name.trimmingCharacters(in: .whitespacesAndNewlines),
            newURL: cleanURL,
            newTokenId: changeCredentials ? tokenId : nil,
            newTokenSecret: changeCredentials ? tokenSecret : nil
        )

        isSaving = false
        dismiss()
    }
}
