import PhotosUI
import SwiftUI

/// Embedded profile editing content (no NavigationStack — lives inside SettingsView's).
/// Avatar + photo picker, name fields with validation.
struct ProfileEditView: View {
    var onAddAccount: ((AuthScreen) -> Void)?
    @Binding var displayName: String
    @Binding var username: String
    let publicKey: String

    @Binding var displayNameError: String?
    @Binding var usernameError: String?
    /// Photo selected but not yet saved — only committed when Done is pressed.
    @Binding var pendingPhoto: UIImage?

    @State private var selectedPhotoItem: PhotosPickerItem?
    @State private var selectedPhoto: UIImage?
    @State private var showAddAccountSheet = false

    private var initials: String {
        RosettaColors.initials(name: displayName, publicKey: publicKey)
    }

    private var avatarColorIndex: Int {
        RosettaColors.avatarColorIndex(for: displayName, publicKey: publicKey)
    }

    var body: some View {
        VStack(spacing: 0) {
            avatarSection
                .padding(.bottom, 24)

            nameSection

            helperText("Enter your name and add an optional profile photo.")
                .padding(.top, 8)
                .padding(.bottom, 24)

            addAccountSection
        }
        .padding(.horizontal, 16)
        .padding(.top, 8)
        .padding(.bottom, 100)
        .task {
            if selectedPhoto == nil {
                selectedPhoto = AvatarRepository.shared.loadAvatar(publicKey: publicKey)
            }
        }
    }
}

// MARK: - Avatar Section

private extension ProfileEditView {
    var avatarSection: some View {
        VStack(spacing: 12) {
            AvatarView(
                initials: initials,
                colorIndex: avatarColorIndex,
                size: 80,
                isSavedMessages: false,
                image: selectedPhoto
            )

            PhotosPicker(selection: $selectedPhotoItem, matching: .images) {
                Text("Set New Photo")
                    .font(.system(size: 15, weight: .medium))
                    .foregroundStyle(RosettaColors.primaryBlue)
            }
            .buttonStyle(.plain)
            .onChange(of: selectedPhotoItem) { _, item in
                Task {
                    if let data = try? await item?.loadTransferable(type: Data.self),
                       let image = UIImage(data: data) {
                        selectedPhoto = image
                        // Preview only — actual save happens when Done is pressed
                        pendingPhoto = image
                    }
                }
            }
        }
    }
}

// MARK: - Name Section

private extension ProfileEditView {
    var nameSection: some View {
        VStack(alignment: .leading, spacing: 0) {
            GlassCard(cornerRadius: 26, fillOpacity: 0.08) {
                VStack(spacing: 0) {
                    // Display Name field
                    HStack {
                        TextField("First Last", text: $displayName)
                            .font(.system(size: 17))
                            .foregroundStyle(RosettaColors.Adaptive.text)
                            .autocorrectionDisabled()
                            .textInputAutocapitalization(.words)
                            .onChange(of: displayName) { _, newValue in
                                let sanitized = ProfileValidator.sanitizeDisplayName(newValue)
                                if sanitized != newValue {
                                    displayName = sanitized
                                }
                                displayNameError = ProfileValidator.validateDisplayName(sanitized)?.errorDescription
                            }

                        if !displayName.isEmpty {
                            Button { displayName = "" } label: {
                                Image(systemName: "xmark.circle.fill")
                                    .font(.system(size: 18))
                                    .foregroundStyle(RosettaColors.tertiaryText)
                            }
                            .buttonStyle(.plain)
                        }
                    }
                    .padding(.horizontal, 16)
                    .frame(height: 52)

                    Divider()
                        .background(RosettaColors.Adaptive.divider)
                        .padding(.leading, 16)

                    // Username field
                    HStack {
                        TextField("Username", text: $username)
                            .font(.system(size: 17))
                            .foregroundStyle(RosettaColors.Adaptive.text)
                            .textInputAutocapitalization(.never)
                            .autocorrectionDisabled()
                            .onChange(of: username) { _, newValue in
                                let lowered = newValue.lowercased()
                                if lowered != newValue {
                                    username = lowered
                                }
                                usernameError = ProfileValidator.validateUsername(lowered)?.errorDescription
                            }

                        if !username.isEmpty {
                            Text("\(username.count)/32")
                                .font(.system(size: 13))
                                .foregroundStyle(RosettaColors.tertiaryText)
                                .padding(.trailing, 4)

                            Button { username = "" } label: {
                                Image(systemName: "xmark.circle.fill")
                                    .font(.system(size: 18))
                                    .foregroundStyle(RosettaColors.tertiaryText)
                            }
                            .buttonStyle(.plain)
                        }
                    }
                    .padding(.horizontal, 16)
                    .frame(height: 52)
                }
            }

            // Validation errors below the card
            if let displayNameError {
                Text(displayNameError)
                    .font(.system(size: 13))
                    .foregroundStyle(RosettaColors.error)
                    .padding(.horizontal, 16)
                    .padding(.top, 8)
            }
            if let usernameError {
                Text(usernameError)
                    .font(.system(size: 13))
                    .foregroundStyle(RosettaColors.error)
                    .padding(.horizontal, 16)
                    .padding(.top, displayNameError != nil ? 2 : 8)
            }
        }
    }
}

// MARK: - Add Account & Helpers

private extension ProfileEditView {
    var addAccountSection: some View {
        GlassCard(cornerRadius: 26, fillOpacity: 0.08) {
            Button {
                showAddAccountSheet = true
            } label: {
                HStack {
                    Spacer()
                    Text("Add Another Account")
                        .font(.system(size: 17))
                        .foregroundStyle(RosettaColors.primaryBlue)
                    Spacer()
                }
                .frame(height: 52)
                .contentShape(Rectangle())
            }
            .buttonStyle(.plain)
        }
        .confirmationDialog(
            "Create account",
            isPresented: $showAddAccountSheet,
            titleVisibility: .visible
        ) {
            Button("Create New Account") {
                // Let dialog dismiss animation complete before heavy state changes
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
                    onAddAccount?(.seedPhrase)
                }
            }
            Button("Import Existing Account") {
                // Let dialog dismiss animation complete before heavy state changes
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
                    onAddAccount?(.importSeed)
                }
            }
            Button("Cancel", role: .cancel) {}
        } message: {
            Text("You may create a new account or import an existing one.")
        }
    }

    func helperText(_ text: String) -> some View {
        Text(text)
            .font(.system(size: 13))
            .foregroundStyle(RosettaColors.secondaryText)
            .frame(maxWidth: .infinity, alignment: .leading)
            .padding(.horizontal, 16)
    }
}

// MARK: - Preview

#Preview {
    NavigationStack {
        ScrollView {
            ProfileEditView(
                displayName: .constant("Gaidar"),
                username: .constant("GaidarTheDev"),
                publicKey: "028d1c9d0000000000000000000000000000000000000000000000000000008e03ec",
                displayNameError: .constant(nil),
                usernameError: .constant(nil),
                pendingPhoto: .constant(nil)
            )
        }
        .background(RosettaColors.Adaptive.background)
    }
}
