import SwiftUI
import ComposeApp

/// Screen for joining an existing residence with a share code - Content only (no navigation bar)
struct OnboardingJoinResidenceContent: View {
    var onJoined: () -> Void

    @StateObject private var viewModel = ResidenceViewModel()
    @State private var shareCode: String = ""
    @State private var isLoading = false
    @State private var errorMessage: String?
    @State private var isAnimating = false
    @FocusState private var isCodeFieldFocused: Bool
    @Environment(\.colorScheme) var colorScheme

    private var isCodeValid: Bool {
        shareCode.count == 6
    }

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

            // Decorative blobs
            GeometryReader { geo in
                OrganicBlobShape(variation: 1)
                    .fill(
                        RadialGradient(
                            colors: [
                                Color.appPrimary.opacity(0.07),
                                Color.appPrimary.opacity(0.02),
                                Color.clear
                            ],
                            center: .center,
                            startRadius: 0,
                            endRadius: geo.size.width * 0.35
                        )
                    )
                    .frame(width: geo.size.width * 0.6, height: geo.size.height * 0.35)
                    .offset(x: -geo.size.width * 0.15, y: geo.size.height * 0.1)
                    .blur(radius: 25)

                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.65, y: geo.size.height * 0.6)
                    .blur(radius: 20)
            }
            .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: "person.2.badge.key.fill")
                                .font(.system(size: 40, weight: .medium))
                                .foregroundColor(.white)
                        }
                        .naturalShadow(.pronounced)
                    }

                    // Title
                    VStack(spacing: 10) {
                        Text("Join a Residence")
                            .font(.system(size: 26, weight: .bold, design: .rounded))
                            .foregroundColor(Color.appTextPrimary)
                            .a11yHeader()

                        Text("Enter the 6-character code shared with you to join an existing home.")
                            .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 share code", text: $shareCode)
                                .font(.system(size: 20, weight: .semibold, design: .monospaced))
                                .textInputAutocapitalization(.characters)
                                .autocorrectionDisabled()
                                .focused($isCodeFieldFocused)
                                .accessibilityHint("Enter 6-character share code")
                                .onChange(of: shareCode) { _, newValue in
                                    // Limit to 6 characters
                                    if newValue.count > 6 {
                                        shareCode = String(newValue.prefix(6))
                                    }
                                    // Clear error when typing
                                    errorMessage = nil
                                }
                        }
                        .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 = 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 isLoading {
                        HStack(spacing: 10) {
                            ProgressView()
                                .tint(Color.appPrimary)
                            Text("Joining residence...")
                                .font(.system(size: 15, weight: .medium))
                                .foregroundColor(Color.appTextSecondary)
                        }
                    }
                }

                Spacer()

                // Join button
                Button(action: joinResidence) {
                    HStack(spacing: 10) {
                        if isLoading {
                            ProgressView()
                                .progressViewStyle(CircularProgressViewStyle(tint: .white))
                        }
                        Text(isLoading ? "Joining..." : "Join Residence")
                            .font(.system(size: 17, weight: .semibold))
                    }
                    .frame(maxWidth: .infinity)
                    .frame(height: 56)
                    .foregroundColor(Color.appTextOnPrimary)
                    .background(
                        isCodeValid && !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(isCodeValid ? .medium : .subtle)
                }
                .disabled(!isCodeValid || isLoading)
                .padding(.horizontal, OrganicSpacing.comfortable)
                .padding(.bottom, OrganicSpacing.airy)
            }
        }
        .onAppear {
            isAnimating = true
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                isCodeFieldFocused = true
            }
        }
        .onDisappear {
            isAnimating = false
        }
    }

    private func joinResidence() {
        guard shareCode.count == 6 else {
            errorMessage = "Share code must be 6 characters"
            return
        }

        isLoading = true
        errorMessage = nil

        viewModel.joinWithCode(code: shareCode) { success in
            isLoading = false
            if success {
                onJoined()
            } else {
                errorMessage = viewModel.errorMessage
            }
        }
    }
}

// MARK: - Preview

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

struct OnboardingJoinResidenceView: View {
    var onJoined: () -> Void
    var onSkip: () -> Void

    var body: some View {
        ZStack {
            WarmGradientBackground()

            VStack(spacing: 0) {
                // Navigation bar
                HStack {
                    Spacer()

                    Button(action: onSkip) {
                        Text("Skip")
                            .font(.system(size: 15, weight: .medium))
                            .foregroundColor(Color.appTextSecondary)
                    }
                }
                .padding(.horizontal, 20)
                .padding(.vertical, 12)

                OnboardingJoinResidenceContent(onJoined: onJoined)
            }
        }
    }
}

#Preview {
    OnboardingJoinResidenceContent(onJoined: {})
}
