import SwiftUI

struct VerifyEmailView: View {
    @StateObject private var viewModel = VerifyEmailViewModel()
    @FocusState private var isFocused: Bool
    var onVerifySuccess: () -> Void
    var onLogout: () -> Void

    var body: some View {
        NavigationStack {
            ZStack {
                WarmGradientBackground()

                ScrollView(showsIndicators: false) {
                    VStack(spacing: OrganicSpacing.spacious) {
                        Spacer()
                            .frame(height: OrganicSpacing.comfortable)

                        // Hero Section
                        VStack(spacing: OrganicSpacing.comfortable) {
                            ZStack {
                                Circle()
                                    .fill(
                                        RadialGradient(
                                            colors: [
                                                Color.appPrimary.opacity(0.15),
                                                Color.appPrimary.opacity(0.05),
                                                Color.clear
                                            ],
                                            center: .center,
                                            startRadius: 0,
                                            endRadius: 60
                                        )
                                    )
                                    .frame(width: 120, height: 120)

                                Image(systemName: "envelope.badge.shield.half.filled")
                                    .font(.system(size: 48, weight: .medium))
                                    .foregroundColor(Color.appPrimary)
                            }

                            VStack(spacing: 8) {
                                Text(L10n.Auth.verifyYourEmail)
                                    .font(.system(size: 26, weight: .bold, design: .rounded))
                                    .foregroundColor(Color.appTextPrimary)

                                Text(L10n.Auth.verifyMustVerify)
                                    .font(.system(size: 15, weight: .medium))
                                    .foregroundColor(Color.appTextSecondary)
                                    .multilineTextAlignment(.center)
                                    .padding(.horizontal)
                            }
                        }

                        // Form Card
                        VStack(spacing: 20) {
                            // Info Banner
                            HStack(spacing: 12) {
                                ZStack {
                                    Circle()
                                        .fill(Color.appAccent.opacity(0.1))
                                        .frame(width: 40, height: 40)
                                    Image(systemName: "exclamationmark.shield.fill")
                                        .font(.system(size: 18, weight: .medium))
                                        .foregroundColor(Color.appAccent)
                                }

                                Text(L10n.Auth.verifyCheckInbox)
                                    .font(.system(size: 14, weight: .semibold))
                                    .foregroundColor(Color.appTextPrimary)

                                Spacer()
                            }
                            .padding(16)
                            .background(Color.appAccent.opacity(0.08))
                            .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))

                            // Code Input
                            VStack(alignment: .leading, spacing: 8) {
                                Text(L10n.Auth.verifyCodeLabel.uppercased())
                                    .font(.system(size: 11, weight: .semibold, design: .rounded))
                                    .foregroundColor(Color.appTextSecondary)
                                    .tracking(1.2)

                                TextField("000000", text: $viewModel.code)
                                    .font(.system(size: 32, weight: .bold, design: .rounded))
                                    .multilineTextAlignment(.center)
                                    .keyboardType(.numberPad)
                                    .focused($isFocused)
                                    .keyboardDismissToolbar()
                                    .padding(20)
                                    .background(Color.appBackgroundPrimary.opacity(0.5))
                                    .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                                    .overlay(
                                        RoundedRectangle(cornerRadius: 16, style: .continuous)
                                            .stroke(isFocused ? Color.appPrimary : Color.appTextSecondary.opacity(0.15), lineWidth: 1.5)
                                    )
                                    .accessibilityIdentifier(AccessibilityIdentifiers.Authentication.verificationCodeField)
                                    .onChange(of: viewModel.code) { _, newValue in
                                        // Filter to only digits and limit to 6
                                        let filtered = newValue.filter { $0.isNumber }
                                        if filtered.count > 6 {
                                            viewModel.code = String(filtered.prefix(6))
                                        } else if filtered != newValue {
                                            viewModel.code = filtered
                                        }

                                        // Auto-submit when 6 digits entered
                                        if viewModel.code.count == 6 && !viewModel.isLoading {
                                            isFocused = false  // Dismiss keyboard
                                            viewModel.verifyEmail()
                                        }
                                    }

                                Text(L10n.Auth.verifyCodeMustBe6)
                                    .font(.system(size: 12, weight: .medium))
                                    .foregroundColor(Color.appTextSecondary)
                            }

                            // Error Message
                            if let errorMessage = viewModel.errorMessage {
                                HStack(spacing: 10) {
                                    Image(systemName: "exclamationmark.circle.fill")
                                        .foregroundColor(Color.appError)
                                    Text(errorMessage)
                                        .font(.system(size: 14, weight: .medium))
                                        .foregroundColor(Color.appError)
                                    Spacer()
                                }
                                .padding(16)
                                .background(Color.appError.opacity(0.1))
                                .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                            }

                            // Verify Button
                            Button(action: {
                                viewModel.verifyEmail()
                            }) {
                                HStack(spacing: 8) {
                                    if viewModel.isLoading {
                                        ProgressView()
                                            .progressViewStyle(CircularProgressViewStyle(tint: .white))
                                    } else {
                                        Image(systemName: "checkmark.shield.fill")
                                    }
                                    Text(viewModel.isLoading ? "Verifying..." : L10n.Auth.verifyEmailButton)
                                        .font(.headline)
                                        .fontWeight(.semibold)
                                }
                                .frame(maxWidth: .infinity)
                                .frame(height: 56)
                                .foregroundColor(Color.appTextOnPrimary)
                                .background(
                                    viewModel.code.count == 6 && !viewModel.isLoading
                                        ? AnyShapeStyle(LinearGradient(colors: [Color.appPrimary, Color.appPrimary.opacity(0.8)], startPoint: .topLeading, endPoint: .bottomTrailing))
                                        : AnyShapeStyle(Color.appTextSecondary)
                                )
                                .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
                                .shadow(
                                    color: viewModel.code.count == 6 && !viewModel.isLoading ? Color.appPrimary.opacity(0.3) : .clear,
                                    radius: 10,
                                    y: 5
                                )
                            }
                            .disabled(viewModel.code.count != 6 || viewModel.isLoading)
                            .accessibilityIdentifier(AccessibilityIdentifiers.Authentication.verifyButton)

                            // Help Text
                            Text(L10n.Auth.verifyHelpText)
                                .font(.system(size: 12, weight: .medium))
                                .foregroundColor(Color.appTextSecondary)
                                .multilineTextAlignment(.center)
                        }
                        .padding(OrganicSpacing.cozy)
                        .background(OrganicVerifyEmailBackground())
                        .clipShape(RoundedRectangle(cornerRadius: 32, style: .continuous))
                        .naturalShadow(.pronounced)
                        .padding(.horizontal, 16)

                        Spacer()
                    }
                }
            }
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: onLogout) {
                        HStack(spacing: 6) {
                            Image(systemName: "rectangle.portrait.and.arrow.right")
                                .font(.system(size: 14, weight: .medium))
                            Text(L10n.Auth.logout)
                                .font(.system(size: 14, weight: .semibold))
                        }
                        .foregroundColor(Color.appTextSecondary)
                        .padding(.horizontal, 12)
                        .padding(.vertical, 8)
                        .background(Color.appBackgroundSecondary.opacity(0.8))
                        .clipShape(Capsule())
                    }
                    .accessibilityIdentifier(AccessibilityIdentifiers.Authentication.verificationLogoutButton)
                }
            }
            .onAppear {
                isFocused = true
            }
            .onChange(of: viewModel.isVerified) { _, isVerified in
                if isVerified {
                    onVerifySuccess()
                }
            }
        }
    }
}

// MARK: - Background

private struct OrganicVerifyEmailBackground: View {
    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        ZStack {
            Color.appBackgroundSecondary

            GeometryReader { geo in
                OrganicBlobShape(variation: 0)
                    .fill(
                        RadialGradient(
                            colors: [
                                Color.appPrimary.opacity(colorScheme == .dark ? 0.08 : 0.05),
                                Color.appPrimary.opacity(0.01)
                            ],
                            center: .center,
                            startRadius: 0,
                            endRadius: geo.size.width * 0.5
                        )
                    )
                    .frame(width: geo.size.width * 0.6, height: geo.size.height * 0.5)
                    .offset(x: geo.size.width * 0.4, y: -geo.size.height * 0.1)
                    .blur(radius: 20)
            }

            GrainTexture(opacity: 0.015)
        }
    }
}

#Preview {
    VerifyEmailView(
        onVerifySuccess: { print("Verified!") },
        onLogout: { print("Logout") }
    )
}
