import SwiftUI

/// Safety screen — Android parity.
/// Shows public/private keys with copy, backup navigation, and delete account.
struct SafetyView: View {
    var onLogout: (() -> Void)?

    @Environment(\.dismiss) private var dismiss
    @State private var copiedPublicKey = false
    @State private var copiedPrivateKey = false
    @State private var showDeleteConfirmation = false
    @State private var navController: UINavigationController?

    private var publicKey: String {
        SessionManager.shared.currentPublicKey
    }

    private var privateKeyHash: String {
        SessionManager.shared.privateKeyHash ?? ""
    }

    var body: some View {
        ZStack(alignment: .topLeading) {
            ScrollView(showsIndicators: false) {
                VStack(spacing: 0) {
                    keysSection
                    actionsSection
                }
                .padding(.horizontal, 16)
                .padding(.top, 60)
                .padding(.bottom, 100)
            }

            // Inline back button — UIKit ComposeGlassBackButton (SVG chevron, identical to Appearance)
            SettingsGlassBackButton {
                dismiss()
            }
            .frame(width: 44, height: 44)
            .padding(.leading, 8)
            .padding(.top, 4)
        }
        .background(
            NavigationControllerAccessor { nav in
                self.navController = nav
            }
        )
        .background(RosettaColors.Adaptive.background)
        .scrollContentBackground(.hidden)
        .navigationBarTitleDisplayMode(.inline)
        .navigationBarBackButtonHidden(true)
        .enableSwipeBack()
        .toolbarBackground(.hidden, for: .navigationBar)
        .alert("Delete Account", isPresented: $showDeleteConfirmation) {
            Button("Cancel", role: .cancel) {}
            Button("Delete Account", role: .destructive) {
                let publicKey = SessionManager.shared.currentPublicKey
                BiometricAuthManager.shared.clearAll(forAccount: publicKey)
                AvatarRepository.shared.removeAvatar(publicKey: publicKey)
                // Start fade overlay FIRST — covers the screen before
                // deleteAccount() triggers setActiveAccount(next) which
                // would cause MainTabView .id() recreation.
                onLogout?()
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.04) {
                    DialogRepository.shared.reset(clearPersisted: true)
                    MessageRepository.shared.reset(clearPersisted: true)
                    let defaults = UserDefaults.standard
                    defaults.removeObject(forKey: "rosetta_recent_searches_\(publicKey)")
                    defaults.removeObject(forKey: "rosetta_last_sync_\(publicKey)")
                    defaults.removeObject(forKey: "backgroundBlurColor_\(publicKey)")
                    SessionManager.shared.endSession()
                    try? AccountManager.shared.deleteAccount()
                }
            }
        } message: {
            Text("Are you sure? This will permanently delete your account from this device. You'll need your seed phrase to recover it.")
        }
    }

    // MARK: - Keys Section

    private var keysSection: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text("KEYS")
                .font(.system(size: 13, weight: .medium))
                .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                .padding(.horizontal, 4)

            SettingsCard {
                VStack(spacing: 0) {
                    copyRow(
                        label: "Public Key",
                        value: publicKey,
                        isCopied: copiedPublicKey,
                        position: .top
                    ) {
                        UIPasteboard.general.string = publicKey
                        copiedPublicKey = true
                        Task { @MainActor in
                            try? await Task.sleep(nanoseconds: 2_000_000_000)
                            copiedPublicKey = false
                        }
                    }

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

                    copyRow(
                        label: "Private Key",
                        value: privateKeyHash,
                        isCopied: copiedPrivateKey,
                        position: .bottom
                    ) {
                        UIPasteboard.general.string = privateKeyHash
                        copiedPrivateKey = true
                        Task { @MainActor in
                            try? await Task.sleep(nanoseconds: 2_000_000_000)
                            copiedPrivateKey = false
                        }
                    }
                }
            }

            Text("Your private key is encrypted. Never share it with anyone.")
                .font(.system(size: 13))
                .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                .frame(maxWidth: .infinity, alignment: .leading)
                .padding(.horizontal, 4)
        }
    }

    // MARK: - Actions Section

    private var actionsSection: some View {
        VStack(alignment: .leading, spacing: 8) {
            SettingsCard {
                VStack(spacing: 0) {
                    Button {
                        let hosting = UIHostingController(rootView: BackupView())
                        hosting.view.backgroundColor = UIColor(RosettaColors.Adaptive.background)
                        navController?.pushViewController(hosting, animated: true)
                    } label: {
                        HStack {
                            Text("Backup")
                                .font(.system(size: 15))
                                .foregroundStyle(RosettaColors.Adaptive.text)

                            Spacer()

                            Image(systemName: "chevron.right")
                                .font(.system(size: 14, weight: .semibold))
                                .foregroundStyle(RosettaColors.tertiaryText)
                        }
                        .padding(.horizontal, 16)
                        .frame(height: 48)
                        .contentShape(Rectangle())
                    }
                    .settingsHighlight(position: .top)

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

                    actionRow(
                        label: "Delete Account",
                        color: RosettaColors.error,
                        showChevron: false,
                        position: .bottom
                    ) {
                        showDeleteConfirmation = true
                    }
                }
            }

            Text("Deleting your account will permanently remove all data from this device and the server.")
                .font(.system(size: 13))
                .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                .frame(maxWidth: .infinity, alignment: .leading)
                .padding(.horizontal, 4)
        }
        .padding(.top, 24)
    }

    // MARK: - Helpers

    private func copyRow(
        label: String,
        value: String,
        isCopied: Bool,
        position: SettingsRowPosition = .alone,
        action: @escaping () -> Void
    ) -> some View {
        Button(action: action) {
            HStack {
                Text(label)
                    .font(.system(size: 15))
                    .foregroundStyle(RosettaColors.Adaptive.text)

                Spacer()

                if isCopied {
                    Text("Copied")
                        .font(.system(size: 15, weight: .medium))
                        .foregroundStyle(RosettaColors.success)
                } else {
                    Text(truncateKey(value))
                        .font(.system(size: 15))
                        .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                        .lineLimit(1)
                }
            }
            .padding(.horizontal, 16)
            .frame(height: 48)
            .contentShape(Rectangle())
        }
        .settingsHighlight(position: position)
    }

    private func actionRow(
        label: String,
        color: Color,
        showChevron: Bool = true,
        position: SettingsRowPosition = .alone,
        action: @escaping () -> Void
    ) -> some View {
        Button(action: action) {
            HStack {
                Text(label)
                    .font(.system(size: 15))
                    .foregroundStyle(color)

                Spacer()

                if showChevron {
                    Image(systemName: "chevron.right")
                        .font(.system(size: 14, weight: .semibold))
                        .foregroundStyle(RosettaColors.tertiaryText)
                }
            }
            .padding(.horizontal, 16)
            .frame(height: 48)
            .contentShape(Rectangle())
        }
        .settingsHighlight(position: position)
    }

    private func truncateKey(_ key: String) -> String {
        guard key.count > 20 else { return key }
        return String(key.prefix(20)) + "..."
    }
}
