import SwiftUI

/// Backup screen — desktop/Android parity.
/// User enters password → decrypts seed phrase → displays 12-word grid.
struct BackupView: View {
    @Environment(\.dismiss) private var dismiss

    @State private var password = ""
    @State private var seedWords: [String] = []
    @State private var isVerifying = false
    @State private var errorMessage: String?
    @State private var isPasswordVisible = false
    @State private var copied = false
    @FocusState private var isPasswordFocused: Bool

    private var isUnlocked: Bool { !seedWords.isEmpty }

    var body: some View {
        ScrollView(showsIndicators: false) {
            VStack(spacing: 0) {
                if isUnlocked {
                    seedPhraseContent
                        .transition(.opacity)
                } else {
                    passwordContent
                        .transition(.opacity)
                }
            }
            .animation(.easeInOut(duration: 0.3), value: isUnlocked)
            .padding(.horizontal, 16)
            .padding(.top, 16)
            .padding(.bottom, 100)
        }
        .background(RosettaColors.Adaptive.background)
        .scrollContentBackground(.hidden)
        .navigationBarTitleDisplayMode(.inline)
        .navigationBarBackButtonHidden(true)
        .enableSwipeBack()
        .toolbar { toolbarContent }
        .toolbarBackground(.hidden, for: .navigationBar)
    }

    // MARK: - Toolbar

    @ToolbarContentBuilder
    private var toolbarContent: some ToolbarContent {
        ToolbarItem(placement: .navigationBarLeading) {
            Button {
                dismiss()
            } label: {
                Image(systemName: "chevron.left")
                    .font(.system(size: 16, weight: .semibold))
                    .foregroundStyle(RosettaColors.Adaptive.text)
                    .frame(width: 44, height: 44)
            }
            .buttonStyle(.plain)
            .glassCircle()
        }
    }

    // MARK: - Password Content

    private var passwordContent: some View {
        VStack(spacing: 24) {
            LottieView(
                animationName: "lock",
                animationSpeed: 1.0
            )
            .frame(width: 120, height: 120)
            .padding(.top, 20)

            VStack(spacing: 8) {
                Text("Enter your password")
                    .font(.system(size: 20, weight: .bold))
                    .foregroundStyle(RosettaColors.Adaptive.text)

                Text("To view your seed phrase, please enter your account password.")
                    .font(.system(size: 15))
                    .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                    .multilineTextAlignment(.center)
                    .padding(.horizontal, 16)
            }

            passwordField

            if let errorMessage {
                Text(errorMessage)
                    .font(.system(size: 13))
                    .foregroundStyle(RosettaColors.error)
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .padding(.horizontal, 4)
            }

            verifyButton
        }
    }

    private var passwordField: some View {
        SettingsCard {
            HStack(spacing: 12) {
                Group {
                    if isPasswordVisible {
                        TextField("Password", text: $password)
                    } else {
                        SecureField("Password", text: $password)
                    }
                }
                .font(.system(size: 17))
                .foregroundStyle(RosettaColors.Adaptive.text)
                .focused($isPasswordFocused)
                .textContentType(.password)
                .autocorrectionDisabled()
                .textInputAutocapitalization(.never)
                .submitLabel(.done)
                .onSubmit { verifyPassword() }

                Button {
                    isPasswordVisible.toggle()
                } label: {
                    Image(systemName: isPasswordVisible ? "eye.slash" : "eye")
                        .font(.system(size: 16))
                        .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                        .frame(width: 32, height: 32)
                }
                .buttonStyle(.plain)
            }
            .padding(.horizontal, 16)
            .frame(height: 52)
        }
        .task {
            // Delay keyboard until push animation finishes
            try? await Task.sleep(nanoseconds: 450_000_000)
            isPasswordFocused = true
        }
    }

    private var verifyButton: some View {
        Button {
            verifyPassword()
        } label: {
            Group {
                if isVerifying {
                    ProgressView()
                        .tint(.white)
                } else {
                    Text("Verify")
                        .font(.system(size: 17, weight: .medium))
                        .foregroundStyle(.white)
                }
            }
            .frame(maxWidth: .infinity)
            .frame(height: 48)
        }
        .buttonStyle(RosettaPrimaryButtonStyle())
        .disabled(password.isEmpty || isVerifying)
        .opacity(password.isEmpty ? 0.5 : 1.0)
    }

    // MARK: - Seed Phrase Content

    private var seedPhraseContent: some View {
        VStack(spacing: 20) {
            warningBanner

            seedPhraseGrid

            copyButton

            Text("Never share your seed phrase with anyone. Anyone with your seed phrase can access your account.")
                .font(.system(size: 13))
                .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                .frame(maxWidth: .infinity, alignment: .leading)
                .padding(.horizontal, 4)
        }
    }

    private var warningBanner: some View {
        SettingsCard {
            HStack(spacing: 12) {
                Image(systemName: "exclamationmark.triangle.fill")
                    .font(.system(size: 20))
                    .foregroundStyle(.orange)

                VStack(alignment: .leading, spacing: 2) {
                    Text("Keep it secret")
                        .font(.system(size: 15, weight: .medium))
                        .foregroundStyle(RosettaColors.Adaptive.text)

                    Text("Do not share your seed phrase with anyone.")
                        .font(.system(size: 13))
                        .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                }

                Spacer()
            }
            .padding(16)
        }
    }

    private var seedPhraseGrid: some View {
        let leftColumn = Array(seedWords.prefix(6))
        let rightColumn = Array(seedWords.dropFirst(6))

        return HStack(alignment: .top, spacing: 12) {
            seedColumn(words: leftColumn, startIndex: 1)
            seedColumn(words: rightColumn, startIndex: 7)
        }
    }

    private func seedColumn(words: [String], startIndex: Int) -> some View {
        VStack(spacing: 10) {
            ForEach(Array(words.enumerated()), id: \.offset) { offset, word in
                let globalIndex = startIndex + offset - 1
                seedWordCard(
                    number: startIndex + offset,
                    word: word,
                    colorIndex: globalIndex
                )
            }
        }
    }

    private func seedWordCard(number: Int, word: String, colorIndex: Int) -> some View {
        let color = RosettaColors.seedWordColors[colorIndex % RosettaColors.seedWordColors.count]

        return HStack(spacing: 8) {
            Text("\(number).")
                .font(.system(size: 15))
                .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                .frame(width: 28, alignment: .trailing)

            Text(word)
                .font(.system(size: 17, weight: .semibold, design: .monospaced))
                .foregroundStyle(color)

            Spacer()
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 14)
        .modifier(BackupSeedCardStyle(color: color))
    }

    private var copyButton: some View {
        Button {
            UIPasteboard.general.string = seedWords.joined(separator: " ")
            copied = true
            Task { @MainActor in
                try? await Task.sleep(nanoseconds: 2_000_000_000)
                copied = false
            }
        } label: {
            HStack(spacing: 8) {
                Image(systemName: copied ? "checkmark" : "doc.on.doc")
                    .font(.system(size: 15))
                Text(copied ? "Copied" : "Copy Seed Phrase")
                    .font(.system(size: 17, weight: .medium))
            }
            .foregroundStyle(.white)
            .frame(maxWidth: .infinity)
            .frame(height: 48)
        }
        .buttonStyle(RosettaPrimaryButtonStyle())
    }

    // MARK: - Password Verification

    private func verifyPassword() {
        guard !password.isEmpty, !isVerifying else { return }
        isVerifying = true
        errorMessage = nil

        // Capture for sendable detached task
        let enteredPassword = password
        let account = AccountManager.shared.currentAccount
        let crypto = CryptoManager.shared

        Task.detached(priority: .userInitiated) {
            do {
                guard let account else {
                    await MainActor.run {
                        errorMessage = "No account found"
                        isVerifying = false
                    }
                    return
                }
                let decrypted = try crypto.decryptWithPassword(
                    account.seedPhraseEncrypted,
                    password: enteredPassword
                )
                guard let phrase = String(data: decrypted, encoding: .utf8) else {
                    throw CryptoError.decryptionFailed
                }
                let words = phrase.components(separatedBy: " ").filter { !$0.isEmpty }
                guard words.count == 12 else {
                    throw CryptoError.decryptionFailed
                }
                await MainActor.run {
                    seedWords = words
                    isVerifying = false
                }
            } catch {
                await MainActor.run {
                    errorMessage = "Wrong password"
                    isVerifying = false
                }
            }
        }
    }
}

// MARK: - Seed Card Style

private struct BackupSeedCardStyle: ViewModifier {
    let color: Color

    func body(content: Content) -> some View {
        content
            .background {
                RoundedRectangle(cornerRadius: 12)
                    .fill(color.opacity(0.12))
                    .overlay {
                        RoundedRectangle(cornerRadius: 12)
                            .stroke(color.opacity(0.18), lineWidth: 0.5)
                    }
            }
            .clipShape(RoundedRectangle(cornerRadius: 12))
    }
}
