import SwiftUI
import AuthenticationServices
import ComposeApp

/// Screen 4: Create Account / Sign In with Apple - Content only (no navigation bar)
struct OnboardingCreateAccountContent: View {
    var onAccountCreated: (Bool) -> Void  // Bool indicates if user is already verified

    @StateObject private var viewModel = RegisterViewModel()
    @StateObject private var appleSignInViewModel = AppleSignInViewModel()
    @State private var showingLoginSheet = false
    @State private var isExpanded = false
    @State private var isAnimating = false
    @ObservedObject private var googleSignInManager = GoogleSignInManager.shared
    @FocusState private var focusedField: Field?
    @Environment(\.colorScheme) var colorScheme

    enum Field {
        case username, email, password, confirmPassword
    }

    private var hasMinLength: Bool { viewModel.password.count >= 8 }
    private var hasUppercase: Bool { viewModel.password.range(of: "[A-Z]", options: .regularExpression) != nil }
    private var hasLowercase: Bool { viewModel.password.range(of: "[a-z]", options: .regularExpression) != nil }
    private var hasDigit: Bool { viewModel.password.range(of: "[0-9]", options: .regularExpression) != nil }
    private var isPasswordComplex: Bool { hasMinLength && hasUppercase && hasLowercase && hasDigit }
    private var passwordsMatch: Bool { !viewModel.password.isEmpty && viewModel.password == viewModel.confirmPassword }

    private var isFormValid: Bool {
        !viewModel.username.isEmpty &&
        !viewModel.email.isEmpty &&
        isPasswordComplex &&
        passwordsMatch
    }

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

            // Decorative blobs
            GeometryReader { geo in
                OrganicBlobShape(variation: 1)
                    .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.25)
                    .offset(x: geo.size.width * 0.55, y: geo.size.height * 0.05)
                    .blur(radius: 20)
            }
            .a11yDecorative()

            ScrollView(showsIndicators: false) {
                VStack(spacing: OrganicSpacing.comfortable) {
                    // Header
                    VStack(spacing: 16) {
                        ZStack {
                            // Pulsing glow
                            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)
                                .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: 80, height: 80)

                                Image(systemName: "person.badge.plus")
                                    .font(.system(size: 36, weight: .medium))
                                    .foregroundColor(.white)
                            }
                            .naturalShadow(.pronounced)
                        }

                        Text("Save your home to your account")
                            .font(.system(size: 24, weight: .bold, design: .rounded))
                            .foregroundColor(Color.appTextPrimary)
                            .multilineTextAlignment(.center)
                            .accessibilityIdentifier(AccessibilityIdentifiers.Onboarding.createAccountTitle)
                            .a11yHeader()

                        Text("Your data will be synced across devices")
                            .font(.system(size: 15, weight: .medium))
                            .foregroundColor(Color.appTextSecondary)
                    }
                    .padding(.top, OrganicSpacing.comfortable)

                    // Sign in with Apple (Primary)
                    VStack(spacing: 14) {
                        SignInWithAppleButton(
                            onRequest: { request in
                                request.requestedScopes = [.fullName, .email]
                            },
                            onCompletion: { _ in }
                        )
                        .frame(height: 56)
                        .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                        .signInWithAppleButtonStyle(.black)
                        .disabled(appleSignInViewModel.isLoading)
                        .opacity(appleSignInViewModel.isLoading ? 0.6 : 1.0)
                        .overlay {
                            Color.clear
                                .contentShape(Rectangle())
                                .onTapGesture {
                                    appleSignInViewModel.signInWithApple()
                                }
                        }

                        if appleSignInViewModel.isLoading {
                            HStack(spacing: 10) {
                                ProgressView()
                                    .tint(Color.appPrimary)
                                Text("Signing in with Apple...")
                                    .font(.system(size: 15, weight: .medium))
                                    .foregroundColor(Color.appTextSecondary)
                            }
                        }

                        if let error = appleSignInViewModel.errorMessage {
                            OrganicErrorMessage(message: error)
                        }

                        // Google Sign-In Button
                        Button(action: {
                            googleSignInManager.signIn()
                        }) {
                            HStack(spacing: 10) {
                                Image(systemName: "globe")
                                    .font(.system(size: 18, weight: .medium))
                                    .foregroundColor(Color.appTextPrimary)
                                Text("Sign in with Google")
                                    .font(.system(size: 17, weight: .medium))
                                    .foregroundColor(Color.appTextPrimary)
                            }
                            .frame(maxWidth: .infinity)
                            .frame(height: 56)
                            .background(Color.appBackgroundSecondary)
                            .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                            .overlay(
                                RoundedRectangle(cornerRadius: 16, style: .continuous)
                                    .stroke(Color.appTextSecondary.opacity(0.3), lineWidth: 1)
                            )
                        }
                    }

                    // Divider
                    OrganicDividerWithText(text: "or")

                    // Create Account Form
                    VStack(spacing: 14) {
                        if !isExpanded {
                            // Collapsed state
                            Button(action: {
                                withAnimation(.spring(response: 0.4, dampingFraction: 0.8)) {
                                    isExpanded = true
                                }
                            }) {
                                HStack(spacing: 12) {
                                    ZStack {
                                        Circle()
                                            .fill(Color.appPrimary.opacity(0.15))
                                            .frame(width: 36, height: 36)

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

                                    Text("Create Account with Email")
                                        .font(.system(size: 17, weight: .semibold))
                                }
                                .frame(maxWidth: .infinity)
                                .frame(height: 56)
                                .foregroundColor(Color.appPrimary)
                                .background(Color.appPrimary.opacity(0.1))
                                .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 16, style: .continuous)
                                        .stroke(Color.appPrimary.opacity(0.2), lineWidth: 1)
                                )
                            }
                            .accessibilityIdentifier(AccessibilityIdentifiers.Onboarding.emailSignUpExpandButton)
                        } else {
                            // Expanded form
                            VStack(spacing: 14) {
                                // Form card
                                VStack(spacing: 16) {
                                    OrganicOnboardingTextField(
                                        icon: "person.fill",
                                        placeholder: "Username",
                                        text: $viewModel.username,
                                        isFocused: focusedField == .username,
                                        accessibilityIdentifier: AccessibilityIdentifiers.Onboarding.usernameField
                                    )
                                    .focused($focusedField, equals: .username)
                                    .textInputAutocapitalization(.never)
                                    .autocorrectionDisabled()
                                    .textContentType(.username)
                                    .accessibilityHint("Enter a unique username")

                                    OrganicOnboardingTextField(
                                        icon: "envelope.fill",
                                        placeholder: "Email",
                                        text: $viewModel.email,
                                        isFocused: focusedField == .email,
                                        accessibilityIdentifier: AccessibilityIdentifiers.Onboarding.emailField
                                    )
                                    .focused($focusedField, equals: .email)
                                    .textInputAutocapitalization(.never)
                                    .autocorrectionDisabled()
                                    .keyboardType(.emailAddress)
                                    .textContentType(.emailAddress)
                                    .accessibilityHint("Enter your email address")

                                    OrganicOnboardingSecureField(
                                        icon: "lock.fill",
                                        placeholder: "Password",
                                        text: $viewModel.password,
                                        isFocused: focusedField == .password,
                                        accessibilityIdentifier: AccessibilityIdentifiers.Onboarding.passwordField
                                    )
                                    .focused($focusedField, equals: .password)
                                    .accessibilityHint("Enter a password with at least 8 characters")

                                    OrganicOnboardingSecureField(
                                        icon: "lock.fill",
                                        placeholder: "Confirm Password",
                                        text: $viewModel.confirmPassword,
                                        isFocused: focusedField == .confirmPassword,
                                        accessibilityIdentifier: AccessibilityIdentifiers.Onboarding.confirmPasswordField
                                    )
                                    .focused($focusedField, equals: .confirmPassword)
                                    .accessibilityHint("Re-enter your password to confirm")

                                    // Password Requirements
                                    if !viewModel.password.isEmpty {
                                        VStack(alignment: .leading, spacing: 6) {
                                            OnboardingPasswordRequirementRow(isMet: hasMinLength, text: "At least 8 characters")
                                            OnboardingPasswordRequirementRow(isMet: hasUppercase, text: "Contains an uppercase letter")
                                            OnboardingPasswordRequirementRow(isMet: hasLowercase, text: "Contains a lowercase letter")
                                            OnboardingPasswordRequirementRow(isMet: hasDigit, text: "Contains a number")
                                            OnboardingPasswordRequirementRow(isMet: passwordsMatch, text: "Passwords match")
                                        }
                                        .padding(12)
                                        .background(Color.appBackgroundPrimary.opacity(0.5))
                                        .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
                                    }
                                }
                                .padding(OrganicSpacing.cozy)
                                .background(
                                    ZStack {
                                        Color.appBackgroundSecondary

                                        GeometryReader { geo in
                                            OrganicBlobShape(variation: 2)
                                                .fill(Color.appPrimary.opacity(colorScheme == .dark ? 0.04 : 0.02))
                                                .frame(width: geo.size.width * 0.4, height: geo.size.height * 0.5)
                                                .offset(x: geo.size.width * 0.65, y: geo.size.height * 0.5)
                                                .blur(radius: 15)
                                        }

                                        GrainTexture(opacity: 0.015)
                                    }
                                )
                                .clipShape(RoundedRectangle(cornerRadius: 24, style: .continuous))
                                .naturalShadow(.medium)

                                if let error = viewModel.errorMessage {
                                    OrganicErrorMessage(message: error)
                                }

                                // Register button
                                Button(action: {
                                    viewModel.register()
                                }) {
                                    HStack(spacing: 10) {
                                        if viewModel.isLoading {
                                            ProgressView()
                                                .progressViewStyle(CircularProgressViewStyle(tint: .white))
                                        }
                                        Text(viewModel.isLoading ? "Creating Account..." : "Create Account")
                                            .font(.system(size: 17, weight: .semibold))
                                    }
                                    .frame(maxWidth: .infinity)
                                    .frame(height: 56)
                                    .foregroundColor(Color.appTextOnPrimary)
                                    .background(
                                        isFormValid && !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(isFormValid ? .medium : .subtle)
                                }
                                .accessibilityIdentifier(AccessibilityIdentifiers.Onboarding.createAccountButton)
                                .disabled(!isFormValid || viewModel.isLoading)
                            }
                            .transition(.opacity.combined(with: .move(edge: .top)))
                        }
                    }

                    // Already have an account
                    HStack(spacing: 6) {
                        Text("Already have an account?")
                            .font(.system(size: 15, weight: .medium))
                            .foregroundColor(Color.appTextSecondary)

                        Button("Log in") {
                            showingLoginSheet = true
                        }
                        .font(.system(size: 15, weight: .semibold))
                        .foregroundColor(Color.appPrimary)
                    }
                    .padding(.top, 8)
                }
                .padding(.horizontal, OrganicSpacing.comfortable)
                .padding(.bottom, OrganicSpacing.airy)
            }
        }
        .sheet(isPresented: $showingLoginSheet) {
            LoginView(onLoginSuccess: {
                showingLoginSheet = false
                onAccountCreated(true)
            })
        }
        .alert("Google Sign-In Error", isPresented: .init(
            get: { googleSignInManager.errorMessage != nil },
            set: { if !$0 { googleSignInManager.errorMessage = nil } }
        )) {
            Button("OK", role: .cancel) { }
        } message: {
            Text(googleSignInManager.errorMessage ?? "An error occurred.")
        }
        .onChange(of: viewModel.isRegistered) { _, isRegistered in
            if isRegistered {
                // Registration successful - user is authenticated but not verified
                onAccountCreated(false)
            }
        }
        .onAppear {
            isAnimating = true
            // Set up Apple Sign In callback
            appleSignInViewModel.onSignInSuccess = { isVerified in
                AuthenticationManager.shared.login(verified: isVerified)
                onAccountCreated(isVerified)
            }
            // Set up Google Sign In callback
            googleSignInManager.onSignInSuccess = { isVerified in
                AuthenticationManager.shared.login(verified: isVerified)
                onAccountCreated(isVerified)
            }
        }
        .onDisappear {
            isAnimating = false
        }
    }
}

// MARK: - Onboarding Password Requirement Row

private struct OnboardingPasswordRequirementRow: View {
    let isMet: Bool
    let text: String

    var body: some View {
        HStack(spacing: 10) {
            Image(systemName: isMet ? "checkmark.circle.fill" : "circle")
                .font(.system(size: 14, weight: .medium))
                .foregroundColor(isMet ? Color.appPrimary : Color.appTextSecondary)

            Text(text)
                .font(.system(size: 13, weight: .medium))
                .foregroundColor(isMet ? Color.appTextPrimary : Color.appTextSecondary)
        }
    }
}

// MARK: - Organic Onboarding TextField

private struct OrganicOnboardingTextField: View {
    let icon: String
    let placeholder: String
    @Binding var text: String
    var isFocused: Bool = false
    var accessibilityIdentifier: String? = nil

    var body: some View {
        HStack(spacing: 14) {
            ZStack {
                Circle()
                    .fill(Color.appPrimary.opacity(0.1))
                    .frame(width: 36, height: 36)

                Image(systemName: icon)
                    .font(.system(size: 15, weight: .medium))
                    .foregroundColor(Color.appPrimary)
            }

            TextField(placeholder, text: $text)
                .font(.system(size: 16, weight: .medium))
                .accessibilityIdentifier(accessibilityIdentifier ?? "")
        }
        .padding(14)
        .background(Color.appBackgroundPrimary.opacity(0.5))
        .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
        .overlay(
            RoundedRectangle(cornerRadius: 14, style: .continuous)
                .stroke(isFocused ? Color.appPrimary : Color.appTextSecondary.opacity(0.2), lineWidth: 1.5)
        )
    }
}

// MARK: - Organic Onboarding Secure Field

private struct OrganicOnboardingSecureField: View {
    let icon: String
    let placeholder: String
    @Binding var text: String
    var isFocused: Bool = false
    var accessibilityIdentifier: String? = nil
    @State private var showPassword = false

    var body: some View {
        HStack(spacing: 14) {
            ZStack {
                Circle()
                    .fill(Color.appPrimary.opacity(0.1))
                    .frame(width: 36, height: 36)

                Image(systemName: icon)
                    .font(.system(size: 15, weight: .medium))
                    .foregroundColor(Color.appPrimary)
            }

            if showPassword {
                TextField(placeholder, text: $text)
                    .font(.system(size: 16, weight: .medium))
                    .textContentType(.password)
                    .accessibilityIdentifier(accessibilityIdentifier ?? "")
            } else {
                SecureField(placeholder, text: $text)
                    .font(.system(size: 16, weight: .medium))
                    .textContentType(.password)
                    .accessibilityIdentifier(accessibilityIdentifier ?? "")
            }

            Button(action: { showPassword.toggle() }) {
                Image(systemName: showPassword ? "eye.slash.fill" : "eye.fill")
                    .font(.system(size: 15, weight: .medium))
                    .foregroundColor(Color.appTextSecondary)
            }
        }
        .padding(14)
        .background(Color.appBackgroundPrimary.opacity(0.5))
        .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
        .overlay(
            RoundedRectangle(cornerRadius: 14, style: .continuous)
                .stroke(isFocused ? Color.appPrimary : Color.appTextSecondary.opacity(0.2), lineWidth: 1.5)
        )
    }
}

// MARK: - Organic Error Message

private struct OrganicErrorMessage: View {
    let message: String

    var body: some View {
        HStack(spacing: 10) {
            Image(systemName: "exclamationmark.circle.fill")
                .foregroundColor(Color.appError)
            Text(message)
                .font(.system(size: 14, weight: .medium))
                .foregroundColor(Color.appError)
            Spacer()
        }
        .padding(14)
        .background(Color.appError.opacity(0.1))
        .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
    }
}

// MARK: - Organic Divider with Text

private struct OrganicDividerWithText: View {
    let text: String

    var body: some View {
        HStack(spacing: 16) {
            Rectangle()
                .fill(
                    LinearGradient(
                        colors: [Color.clear, Color.appTextSecondary.opacity(0.25)],
                        startPoint: .leading,
                        endPoint: .trailing
                    )
                )
                .frame(height: 1)

            Text(text)
                .font(.system(size: 14, weight: .medium))
                .foregroundColor(Color.appTextSecondary)

            Rectangle()
                .fill(
                    LinearGradient(
                        colors: [Color.appTextSecondary.opacity(0.25), Color.clear],
                        startPoint: .leading,
                        endPoint: .trailing
                    )
                )
                .frame(height: 1)
        }
    }
}

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

struct OnboardingCreateAccountView: View {
    var onAccountCreated: (Bool) -> Void
    var onBack: () -> Void

    var body: some View {
        ZStack {
            WarmGradientBackground()

            VStack(spacing: 0) {
                // Navigation bar
                HStack {
                    Button(action: onBack) {
                        ZStack {
                            Circle()
                                .fill(Color.appPrimary.opacity(0.1))
                                .frame(width: 36, height: 36)

                            Image(systemName: "chevron.left")
                                .font(.system(size: 14, weight: .semibold))
                                .foregroundColor(Color.appPrimary)
                        }
                    }

                    Spacer()

                    OnboardingProgressIndicator(currentStep: 3, totalSteps: 5)

                    Spacer()

                    // Invisible spacer for alignment
                    Circle()
                        .fill(Color.clear)
                        .frame(width: 36, height: 36)
                }
                .padding(.horizontal, 20)
                .padding(.vertical, 12)

                OnboardingCreateAccountContent(onAccountCreated: onAccountCreated)
            }
        }
    }
}

// MARK: - Preview

#Preview {
    OnboardingCreateAccountContent(onAccountCreated: { _ in })
}
