import SwiftUI
import ComposeApp

/// Screen 5: Email verification during onboarding - Content only (no navigation bar)
struct OnboardingVerifyEmailContent: View {
    var onVerified: () -> Void

    @StateObject private var viewModel = VerifyEmailViewModel()
    @FocusState private var isCodeFieldFocused: Bool
    @State private var hasCalledOnVerified = false
    @State private var isAnimating = false
    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        ZStack {
            WarmGradientBackground()
                .a11yDecorative()

            // Decorative blobs
            GeometryReader { geo in
                OrganicBlobShape(variation: 0)
                    .fill(
                        RadialGradient(
                            colors: [
                                Color.appPrimary.opacity(0.06),
                                Color.appPrimary.opacity(0.01),
                                Color.clear
                            ],
                            center: .center,
                            startRadius: 0,
                            endRadius: geo.size.width * 0.3
                        )
                    )
                    .frame(width: geo.size.width * 0.5, height: geo.size.height * 0.3)
                    .offset(x: -geo.size.width * 0.1, y: geo.size.height * 0.1)
                    .blur(radius: 20)

                OrganicBlobShape(variation: 2)
                    .fill(
                        RadialGradient(
                            colors: [
                                Color.appAccent.opacity(0.05),
                                Color.appAccent.opacity(0.01),
                                Color.clear
                            ],
                            center: .center,
                            startRadius: 0,
                            endRadius: geo.size.width * 0.25
                        )
                    )
                    .frame(width: geo.size.width * 0.4, height: geo.size.height * 0.25)
                    .offset(x: geo.size.width * 0.6, y: geo.size.height * 0.65)
                    .blur(radius: 15)
            }
            .a11yDecorative()

            VStack(spacing: 0) {
                Spacer()

                // Content
                VStack(spacing: OrganicSpacing.comfortable) {
                    // Icon with pulsing glow
                    ZStack {
                        Circle()
                            .fill(
                                RadialGradient(
                                    colors: [
                                        Color.appPrimary.opacity(0.15),
                                        Color.appPrimary.opacity(0.05),
                                        Color.clear
                                    ],
                                    center: .center,
                                    startRadius: 0,
                                    endRadius: 70
                                )
                            )
                            .frame(width: 140, height: 140)
                            .scaleEffect(isAnimating ? 1.1 : 1.0)
                            .animation(
                                isAnimating
                                    ? Animation.easeInOut(duration: 2.5).repeatForever(autoreverses: true)
                                    : .default,
                                value: isAnimating
                            )

                        ZStack {
                            Circle()
                                .fill(
                                    LinearGradient(
                                        colors: [Color.appPrimary, Color.appPrimary.opacity(0.8)],
                                        startPoint: .topLeading,
                                        endPoint: .bottomTrailing
                                    )
                                )
                                .frame(width: 90, height: 90)

                            Image(systemName: "envelope.badge.fill")
                                .font(.system(size: 40, weight: .medium))
                                .foregroundColor(.white)
                        }
                        .naturalShadow(.pronounced)
                    }

                    // Title
                    VStack(spacing: 10) {
                        Text("Verify your email")
                            .font(.system(size: 26, weight: .bold, design: .rounded))
                            .foregroundColor(Color.appTextPrimary)
                            .accessibilityIdentifier(AccessibilityIdentifiers.Onboarding.verifyEmailTitle)
                            .a11yHeader()

                        Text("We sent a 6-digit code to your email address. Enter it below to verify your account.")
                            .font(.system(size: 15, weight: .medium))
                            .foregroundColor(Color.appTextSecondary)
                            .multilineTextAlignment(.center)
                            .lineSpacing(4)
                            .padding(.horizontal, 20)
                    }

                    // Code input card
                    VStack(spacing: 16) {
                        HStack(spacing: 14) {
                            ZStack {
                                Circle()
                                    .fill(Color.appPrimary.opacity(0.1))
                                    .frame(width: 40, height: 40)

                                Image(systemName: "key.fill")
                                    .font(.system(size: 17, weight: .medium))
                                    .foregroundColor(Color.appPrimary)
                            }

                            TextField("Enter 6-digit code", text: $viewModel.code)
                                .font(.system(size: 20, weight: .semibold, design: .monospaced))
                                .keyboardType(.numberPad)
                                .textContentType(.oneTimeCode)
                                .focused($isCodeFieldFocused)
                                .accessibilityIdentifier(AccessibilityIdentifiers.Onboarding.verificationCodeField)
                                .accessibilityHint("Enter 6-digit verification code")
                                .keyboardDismissToolbar()
                                .onChange(of: viewModel.code) { _, newValue in
                                    // Filter to digits only and truncate to 6 in one pass to prevent re-triggering
                                    let filtered = String(newValue.filter { $0.isNumber }.prefix(6))
                                    if filtered != newValue {
                                        viewModel.code = filtered
                                    }
                                    // Auto-verify when 6 digits entered
                                    if filtered.count == 6 {
                                        viewModel.verifyEmail()
                                    }
                                }
                        }
                        .padding(18)
                        .background(
                            ZStack {
                                Color.appBackgroundSecondary
                                GrainTexture(opacity: 0.01)
                            }
                        )
                        .clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
                        .overlay(
                            RoundedRectangle(cornerRadius: 20, style: .continuous)
                                .stroke(isCodeFieldFocused ? Color.appPrimary : Color.appTextSecondary.opacity(0.2), lineWidth: 2)
                        )
                        .naturalShadow(.medium)
                    }
                    .padding(.horizontal, OrganicSpacing.comfortable)

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

                    // Loading indicator
                    if viewModel.isLoading {
                        HStack(spacing: 10) {
                            ProgressView()
                                .tint(Color.appPrimary)
                            Text("Verifying...")
                                .font(.system(size: 15, weight: .medium))
                                .foregroundColor(Color.appTextSecondary)
                        }
                    }

                    // Resend code hint
                    HStack(alignment: .top, spacing: 6) {
                        Image(systemName: "info.circle.fill")
                            .font(.system(size: 13))
                            .foregroundColor(Color.appTextSecondary.opacity(0.7))

                        Text("Didn't receive a code? Check your spam folder or re-register")
                            .font(.system(size: 13, weight: .medium))
                            .foregroundColor(Color.appTextSecondary)
                            .multilineTextAlignment(.leading)
                            .fixedSize(horizontal: false, vertical: true)
                    }
                    .padding(.horizontal, 16)
                    .padding(.top, 8)
                }

                Spacer()

                // Verify button
                Button(action: {
                    viewModel.verifyEmail()
                }) {
                    HStack(spacing: 10) {
                        if viewModel.isLoading {
                            ProgressView()
                                .progressViewStyle(CircularProgressViewStyle(tint: .white))
                        }
                        Text(viewModel.isLoading ? "Verifying..." : "Verify")
                            .font(.system(size: 17, weight: .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.85)], startPoint: .topLeading, endPoint: .bottomTrailing))
                            : AnyShapeStyle(Color.appTextSecondary.opacity(0.4))
                    )
                    .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                    .naturalShadow(viewModel.code.count == 6 ? .medium : .subtle)
                }
                .accessibilityIdentifier(AccessibilityIdentifiers.Onboarding.verifyButton)
                .disabled(viewModel.code.count != 6 || viewModel.isLoading)
                .padding(.horizontal, OrganicSpacing.comfortable)
                .padding(.bottom, OrganicSpacing.airy)
            }
        }
        .onAppear {
            print("🏠 ONBOARDING: OnboardingVerifyEmailContent appeared")
            isAnimating = true
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                isCodeFieldFocused = true
            }
        }
        .onDisappear {
            isAnimating = false
        }
        .onReceive(viewModel.$isVerified) { isVerified in
            print("🏠 ONBOARDING: onReceive isVerified = \(isVerified), hasCalledOnVerified = \(hasCalledOnVerified)")
            if isVerified && !hasCalledOnVerified {
                hasCalledOnVerified = true
                print("🏠 ONBOARDING: Calling onVerified callback FIRST (before markVerified)")
                // CRITICAL: Call onVerified FIRST so coordinator can create residence
                // BEFORE markVerified changes auth state and disposes this view
                onVerified()
            }
        }
    }
}

// MARK: - Legacy wrapper with navigation bar (for backwards compatibility)

struct OnboardingVerifyEmailView: View {
    var onVerified: () -> Void
    var onLogout: () -> Void

    var body: some View {
        ZStack {
            WarmGradientBackground()

            VStack(spacing: 0) {
                // Navigation bar
                HStack {
                    // Logout option
                    Button(action: onLogout) {
                        HStack(spacing: 6) {
                            Image(systemName: "arrow.left")
                                .font(.system(size: 14, weight: .medium))
                            Text("Back")
                                .font(.system(size: 15, weight: .medium))
                        }
                        .foregroundColor(Color.appPrimary)
                    }

                    Spacer()

                    OnboardingProgressIndicator(currentStep: 4, totalSteps: 5)

                    Spacer()

                    // Invisible spacer for alignment
                    Text("Back")
                        .font(.system(size: 15, weight: .medium))
                        .opacity(0)
                }
                .padding(.horizontal, 20)
                .padding(.vertical, 12)

                OnboardingVerifyEmailContent(onVerified: onVerified)
            }
        }
    }
}

// MARK: - Preview

#Preview {
    OnboardingVerifyEmailContent(onVerified: {})
}
