import SwiftUI
import ComposeApp

struct RegisterView: View {
    @Binding var isPresented: Bool
    var onVerified: (() -> Void)?
    @StateObject private var viewModel = RegisterViewModel()
    @FocusState private var focusedField: Field?
    @State private var isPasswordVisible = false
    @State private var isConfirmPasswordVisible = false
    @State private var verificationCompleted = false

    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 passwordsMatch: Bool { !viewModel.password.isEmpty && viewModel.password == viewModel.confirmPassword }
    private var isPasswordComplex: Bool { hasMinLength && hasUppercase && hasLowercase && hasDigit }

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

    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: "person.badge.plus")
                                    .font(.system(size: 48, weight: .medium))
                                    .foregroundColor(Color.appPrimary)
                            }

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

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

                        // Registration Card
                        VStack(spacing: 20) {
                            // Username Field
                            OrganicTextField(
                                label: L10n.Auth.accountInfo,
                                placeholder: L10n.Auth.registerUsername,
                                text: $viewModel.username,
                                icon: "person.fill",
                                isFocused: focusedField == .username,
                                accessibilityId: AccessibilityIdentifiers.Authentication.registerUsernameField
                            )
                            .focused($focusedField, equals: .username)
                            .textInputAutocapitalization(.never)
                            .autocorrectionDisabled()
                            .textContentType(.username)
                            .submitLabel(.next)
                            .onSubmit { focusedField = .email }

                            // Email Field
                            OrganicTextField(
                                label: nil,
                                placeholder: L10n.Auth.registerEmail,
                                text: $viewModel.email,
                                icon: "envelope.fill",
                                isFocused: focusedField == .email,
                                accessibilityId: AccessibilityIdentifiers.Authentication.registerEmailField
                            )
                            .focused($focusedField, equals: .email)
                            .textInputAutocapitalization(.never)
                            .autocorrectionDisabled()
                            .keyboardType(.emailAddress)
                            .textContentType(.emailAddress)
                            .submitLabel(.next)
                            .onSubmit { focusedField = .password }

                            OrganicDivider()
                                .padding(.vertical, 4)

                            // Password Field
                            OrganicSecureField(
                                label: L10n.Auth.security,
                                placeholder: L10n.Auth.registerPassword,
                                text: $viewModel.password,
                                isVisible: $isPasswordVisible,
                                isFocused: focusedField == .password,
                                accessibilityId: AccessibilityIdentifiers.Authentication.registerPasswordField
                            )
                            .focused($focusedField, equals: .password)
                            .textContentType(UITestRuntime.isEnabled ? nil : .newPassword)
                            .submitLabel(.next)
                            .onSubmit { focusedField = .confirmPassword }

                            // Confirm Password Field
                            OrganicSecureField(
                                label: nil,
                                placeholder: L10n.Auth.registerConfirmPassword,
                                text: $viewModel.confirmPassword,
                                isVisible: $isConfirmPasswordVisible,
                                isFocused: focusedField == .confirmPassword,
                                accessibilityId: AccessibilityIdentifiers.Authentication.registerConfirmPasswordField
                            )
                            .focused($focusedField, equals: .confirmPassword)
                            .textContentType(UITestRuntime.isEnabled ? nil : .newPassword)
                            .submitLabel(.go)
                            .onSubmit { viewModel.register() }

                            // Password Requirements
                            if !viewModel.password.isEmpty {
                                VStack(alignment: .leading, spacing: 8) {
                                    Text("PASSWORD REQUIREMENTS")
                                        .font(.system(size: 11, weight: .semibold, design: .rounded))
                                        .foregroundColor(Color.appTextSecondary)
                                        .tracking(1.2)

                                    VStack(alignment: .leading, spacing: 6) {
                                        PasswordRequirementRow(isMet: hasMinLength, text: "At least 8 characters")
                                        PasswordRequirementRow(isMet: hasUppercase, text: "Contains an uppercase letter")
                                        PasswordRequirementRow(isMet: hasLowercase, text: "Contains a lowercase letter")
                                        PasswordRequirementRow(isMet: hasDigit, text: "Contains a number")
                                        PasswordRequirementRow(isMet: passwordsMatch, text: "Passwords match")
                                    }
                                    .padding(12)
                                    .background(Color.appBackgroundPrimary.opacity(0.5))
                                    .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
                                }
                            }

                            // 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))
                                .accessibilityIdentifier(AccessibilityIdentifiers.Authentication.registerErrorMessage)
                            }

                            // Register Button
                            Button(action: viewModel.register) {
                                HStack(spacing: 8) {
                                    if viewModel.isLoading {
                                        ProgressView()
                                            .progressViewStyle(CircularProgressViewStyle(tint: .white))
                                    }
                                    Text(viewModel.isLoading ? L10n.Auth.creatingAccount : L10n.Auth.registerButton)
                                        .font(.headline)
                                        .fontWeight(.semibold)
                                }
                                .frame(maxWidth: .infinity)
                                .frame(height: 56)
                                .foregroundColor(Color.appTextOnPrimary)
                                .background(
                                    isFormValid && !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: isFormValid && !viewModel.isLoading ? Color.appPrimary.opacity(0.3) : .clear,
                                    radius: 10,
                                    y: 5
                                )
                            }
                            .disabled(!isFormValid || viewModel.isLoading)
                            .accessibilityIdentifier(AccessibilityIdentifiers.Authentication.registerButton)
                            .accessibilityHint("Double tap to create account")

                            // Login Link
                            HStack(spacing: 6) {
                                Text(L10n.Auth.alreadyHaveAccount)
                                    .font(.system(size: 15, weight: .medium))
                                    .foregroundColor(Color.appTextSecondary)

                                Button(L10n.Auth.signIn) {
                                    isPresented = false
                                }
                                .font(.system(size: 15, weight: .bold, design: .rounded))
                                .foregroundColor(Color.appPrimary)
                            }
                            .padding(.top, 8)
                        }
                        .padding(OrganicSpacing.cozy)
                        .background(OrganicFormBackground())
                        .clipShape(RoundedRectangle(cornerRadius: 32, style: .continuous))
                        .naturalShadow(.pronounced)
                        .padding(.horizontal, 16)

                        Spacer()
                    }
                }
            }
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button(action: { isPresented = false }) {
                        Image(systemName: "xmark")
                            .font(.system(size: 14, weight: .semibold))
                            .foregroundColor(Color.appTextSecondary)
                            .padding(8)
                            .background(Color.appBackgroundSecondary.opacity(0.8))
                            .clipShape(Circle())
                    }
                    .accessibilityIdentifier(AccessibilityIdentifiers.Authentication.registerCancelButton)
                }
            }
            .fullScreenCover(isPresented: $viewModel.isRegistered, onDismiss: {
                // fullScreenCover is fully removed from the UIKit presentation stack.
                // Now safe to dismiss the RegisterView sheet. Auth state is set in
                // LoginView's sheet onDismiss after this sheet also finishes dismissing.
                if verificationCompleted {
                    onVerified?()
                    isPresented = false
                }
            }) {
                VerifyEmailView(
                    onVerifySuccess: {
                        verificationCompleted = true
                        viewModel.isRegistered = false
                    },
                    onLogout: {
                        AuthenticationManager.shared.logout()
                        viewModel.isRegistered = false
                        isPresented = false
                    }
                )
            }
            .onAppear {
                AnalyticsManager.shared.trackScreen(.registration)
            }
        }
    }
}

// MARK: - Organic Text Field

private struct OrganicTextField: View {
    let label: String?
    let placeholder: String
    @Binding var text: String
    let icon: String
    var isFocused: Bool = false
    var accessibilityId: String? = nil

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            if let label = label {
                Text(label.uppercased())
                    .font(.system(size: 11, weight: .semibold, design: .rounded))
                    .foregroundColor(Color.appTextSecondary)
                    .tracking(1.2)
            }

            HStack(spacing: 12) {
                ZStack {
                    Circle()
                        .fill(Color.appPrimary.opacity(0.1))
                        .frame(width: 32, height: 32)
                    Image(systemName: icon)
                        .font(.system(size: 14, weight: .medium))
                        .foregroundColor(Color.appPrimary)
                }

                TextField(placeholder, text: $text)
                    .font(.system(size: 16, weight: .medium))
                    .accessibilityIdentifier(accessibilityId ?? "")
            }
            .padding(16)
            .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)
            )
            .animation(.easeInOut(duration: 0.2), value: isFocused)
        }
    }
}

// MARK: - Organic Secure Field

private struct OrganicSecureField: View {
    let label: String?
    let placeholder: String
    @Binding var text: String
    @Binding var isVisible: Bool
    var isFocused: Bool = false
    var accessibilityId: String? = nil

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            if let label = label {
                Text(label.uppercased())
                    .font(.system(size: 11, weight: .semibold, design: .rounded))
                    .foregroundColor(Color.appTextSecondary)
                    .tracking(1.2)
            }

            HStack(spacing: 12) {
                ZStack {
                    Circle()
                        .fill(Color.appPrimary.opacity(0.1))
                        .frame(width: 32, height: 32)
                    Image(systemName: "lock.fill")
                        .font(.system(size: 14, weight: .medium))
                        .foregroundColor(Color.appPrimary)
                }

                Group {
                    if isVisible {
                        TextField(placeholder, text: $text)
                            .accessibilityIdentifier(accessibilityId ?? "")
                    } else {
                        SecureField(placeholder, text: $text)
                            .accessibilityIdentifier(accessibilityId ?? "")
                    }
                }
                .font(.system(size: 16, weight: .medium))

                Button(action: { isVisible.toggle() }) {
                    Image(systemName: isVisible ? "eye.slash.fill" : "eye.fill")
                        .font(.system(size: 16, weight: .medium))
                        .foregroundColor(Color.appTextSecondary)
                }
                .accessibilityLabel("Toggle password visibility")
            }
            .padding(16)
            .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)
            )
            .animation(.easeInOut(duration: 0.2), value: isFocused)
        }
    }
}

// MARK: - Password Requirement Row

private struct PasswordRequirementRow: 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 Form Background

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

    var body: some View {
        ZStack {
            Color.appBackgroundSecondary

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

            GrainTexture(opacity: 0.015)
        }
    }
}

#Preview {
    RegisterView(isPresented: .constant(true))
}
