import SwiftUI
import VoiceCatCore

struct PermissionsView: View {
    let user: User
    @Bindable var session: SessionState
    @Environment(\.dismiss) private var dismiss

    @State private var canCreateTempChannel = false
    @State private var canKick = false
    @State private var canBan = false
    @State private var canMoveUsers = false
    @State private var canAdminAccounts = false
    @State private var isAdmin = false

    var body: some View {
        NavigationStack {
            Form {
                Section("Permissions for \(user.nickname)") {
                    Toggle("Create Temp Channels", isOn: $canCreateTempChannel)
                        .accessibilityLabel("Can create temporary channels")
                    Toggle("Kick Users", isOn: $canKick)
                        .accessibilityLabel("Can kick users")
                    Toggle("Ban Users", isOn: $canBan)
                        .accessibilityLabel("Can ban users")
                    Toggle("Move Users", isOn: $canMoveUsers)
                        .accessibilityLabel("Can move users between channels")
                    Toggle("Manage Accounts", isOn: $canAdminAccounts)
                        .accessibilityLabel("Can manage server accounts")
                }

                Section {
                    Toggle("Administrator", isOn: $isAdmin)
                        .foregroundStyle(isAdmin ? .orange : .primary)
                        .accessibilityLabel("Full administrator access")
                } footer: {
                    Text("Administrators bypass all permission checks.")
                        .font(.caption)
                }
            }
            .navigationTitle("Permissions")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") { dismiss() }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button("Save") {
                        let perms = Permissions(
                            canCreateTempChannel: canCreateTempChannel,
                            canKick: canKick,
                            canBan: canBan,
                            canMoveUsers: canMoveUsers,
                            canAdminAccounts: canAdminAccounts,
                            isAdmin: isAdmin)
                        session.setPermissions(user.id, perms: perms)
                        dismiss()
                    }
                }
            }
        }
    }
}
