import SwiftUI

/// Screen 2: Features showcase - Wow the user with what honeyDue can do
struct OnboardingValuePropsContent: View {
    var onContinue: () -> Void

    @State private var currentPage = 0

    private let features: [FeatureHighlight] = [
        FeatureHighlight(
            icon: "clock.badge.checkmark.fill",
            title: "Never Forget Again",
            subtitle: "Your memory just got an upgrade",
            description: "Smart reminders keep you on top of furnace filters, gutter cleaning, and everything in between. No more \"when did I last...?\" moments.",
            gradient: [Color.appPrimary, Color.appSecondary],
            statNumber: "$6,000+",
            statLabel: "spent yearly on repairs that could've been prevented"
        ),
        FeatureHighlight(
            icon: "doc.text.fill",
            title: "Warranties at Your Fingertips",
            subtitle: "No more digging through drawers",
            description: "Snap a photo of your receipts and warranties. When something breaks, you'll know exactly what's covered—instantly.",
            gradient: [Color.appAccent, Color(hex: "#FF9500") ?? .orange],
            statNumber: "47%",
            statLabel: "of homebuyers lack emergency funds for repairs"
        ),
        FeatureHighlight(
            icon: "person.2.fill",
            title: "The Whole Family's In",
            subtitle: "Teamwork makes the dream work",
            description: "Share your home with family members. Everyone sees what needs doing, and nobody can claim they \"didn't know.\"",
            gradient: [Color(hex: "#AF52DE") ?? .purple, Color(hex: "#BF5AF2") ?? .purple],
            statNumber: "56%",
            statLabel: "say sharing chores is key to a happy home"
        ),
        FeatureHighlight(
            icon: "bell.badge.fill",
            title: "Smart Notifications",
            subtitle: "Act right from your lock screen",
            description: "Get actionable reminders that let you complete tasks right from the notification. No need to even open the app.",
            gradient: [Color(hex: "#FF3B30") ?? .red, Color(hex: "#FF6961") ?? .red],
            statNumber: "3x",
            statLabel: "faster task completion with actionable notifications"
        ),
        FeatureHighlight(
            icon: "square.grid.2x2.fill",
            title: "Home Screen Widgets",
            subtitle: "Your tasks at a glance",
            description: "Quick access to upcoming tasks and reminders directly from your home screen. Stay on top of maintenance without opening the app.",
            gradient: [Color(hex: "#007AFF") ?? .blue, Color(hex: "#5AC8FA") ?? .blue],
            statNumber: "68%",
            statLabel: "of widget users complete tasks on time"
        )
    ]

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

            VStack(spacing: 0) {
                // Feature cards in a tab view
                TabView(selection: $currentPage) {
                    ForEach(Array(features.enumerated()), id: \.offset) { index, feature in
                        OrganicFeatureCard(feature: feature, isActive: currentPage == index)
                            .tag(index)
                            .padding(.horizontal, 20)
                    }
                }
                .accessibilityIdentifier(AccessibilityIdentifiers.Onboarding.valuePropsTitle)
                .tabViewStyle(.page(indexDisplayMode: .never))
                .frame(maxHeight: .infinity)

                // Custom page indicator
                HStack(spacing: 10) {
                    ForEach(0..<features.count, id: \.self) { index in
                        Capsule()
                            .fill(currentPage == index ? Color.appPrimary : Color.appTextSecondary.opacity(0.25))
                            .frame(width: currentPage == index ? 28 : 8, height: 8)
                            .animation(.spring(response: 0.3), value: currentPage)
                    }
                }
                .padding(.bottom, OrganicSpacing.comfortable)

                // Continue button
                Button(action: onContinue) {
                    HStack(spacing: 10) {
                        Text("I'm Ready!")
                            .font(.system(size: 17, weight: .bold))

                        Image(systemName: "arrow.right")
                            .font(.system(size: 16, weight: .bold))
                    }
                    .frame(maxWidth: .infinity)
                    .frame(height: 56)
                    .foregroundColor(Color.appTextOnPrimary)
                    .background(
                        LinearGradient(
                            colors: [Color.appPrimary, Color.appSecondary],
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    )
                    .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                    .naturalShadow(.medium)
                }
                .accessibilityIdentifier(AccessibilityIdentifiers.Onboarding.valuePropsNextButton)
                .accessibilityHint("Double tap to continue to the next step")
                .padding(.horizontal, OrganicSpacing.comfortable)
                .padding(.bottom, OrganicSpacing.airy)
            }
        }
    }
}

// MARK: - Feature Highlight Model

struct FeatureHighlight: Identifiable {
    let id = UUID()
    let icon: String
    let title: String
    let subtitle: String
    let description: String
    let gradient: [Color]
    let statNumber: String
    let statLabel: String
}

// MARK: - Organic Feature Card

struct OrganicFeatureCard: View {
    let feature: FeatureHighlight
    let isActive: Bool

    @State private var appeared = false
    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        VStack(spacing: OrganicSpacing.cozy) {
            Spacer(minLength: 16)

            // Large icon with gradient background
            ZStack {
                // Outer glow
                Circle()
                    .fill(
                        RadialGradient(
                            colors: [feature.gradient[0].opacity(0.25), Color.clear],
                            center: .center,
                            startRadius: 30,
                            endRadius: 90
                        )
                    )
                    .frame(width: 180, height: 180)
                    .scaleEffect(appeared ? 1 : 0.8)
                    .opacity(appeared ? 1 : 0)
                    .a11yDecorative()

                // Icon circle
                ZStack {
                    Circle()
                        .fill(
                            LinearGradient(
                                colors: feature.gradient,
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .frame(width: 100, height: 100)

                    Image(systemName: feature.icon)
                        .font(.system(size: 44))
                        .foregroundColor(.white)
                }
                .naturalShadow(.pronounced)
            }
            .scaleEffect(appeared ? 1 : 0.5)
            .animation(.spring(response: 0.5, dampingFraction: 0.7), value: appeared)

            // Text content
            VStack(spacing: 10) {
                Text(feature.title)
                    .font(.system(size: 24, weight: .bold, design: .rounded))
                    .foregroundColor(Color.appTextPrimary)
                    .multilineTextAlignment(.center)
                    .a11yHeader()

                Text(feature.subtitle)
                    .font(.system(size: 15, weight: .semibold))
                    .foregroundStyle(
                        LinearGradient(
                            colors: feature.gradient,
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    )
                    .multilineTextAlignment(.center)

                Text(feature.description)
                    .font(.system(size: 15, weight: .medium))
                    .foregroundColor(Color.appTextSecondary)
                    .multilineTextAlignment(.center)
                    .lineSpacing(4)
                    .padding(.horizontal, 8)
                    .fixedSize(horizontal: false, vertical: true)
            }
            .opacity(appeared ? 1 : 0)
            .offset(y: appeared ? 0 : 20)
            .animation(.easeOut(duration: 0.4).delay(0.2), value: appeared)

            // Stat highlight card
            VStack(spacing: 6) {
                Text(feature.statNumber)
                    .font(.system(size: 36, weight: .bold, design: .rounded))
                    .foregroundStyle(
                        LinearGradient(
                            colors: feature.gradient,
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    )

                Text(feature.statLabel)
                    .font(.system(size: 13, weight: .medium))
                    .foregroundColor(Color.appTextSecondary)
                    .multilineTextAlignment(.center)
                    .fixedSize(horizontal: false, vertical: true)
            }
            .padding(.horizontal, OrganicSpacing.cozy)
            .padding(.vertical, 16)
            .frame(maxWidth: .infinity)
            .background(
                ZStack {
                    Color.appBackgroundSecondary

                    // Subtle blob accent
                    GeometryReader { geo in
                        OrganicBlobShape(variation: 1)
                            .fill(feature.gradient[0].opacity(colorScheme == .dark ? 0.06 : 0.04))
                            .frame(width: geo.size.width * 0.4, height: geo.size.height * 0.8)
                            .offset(x: geo.size.width * 0.6, y: 0)
                            .blur(radius: 15)
                    }

                    GrainTexture(opacity: 0.015)
                }
            )
            .clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
            .naturalShadow(.subtle)
            .opacity(appeared ? 1 : 0)
            .animation(.easeOut(duration: 0.4).delay(0.4), value: appeared)

            Spacer(minLength: 16)
        }
        .onChange(of: isActive) { _, newValue in
            if newValue {
                appeared = false
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                    appeared = true
                }
            }
        }
        .onAppear {
            if isActive {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    appeared = true
                }
            }
        }
    }
}

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

struct OnboardingValuePropsView: View {
    var onContinue: () -> Void
    var onSkip: () -> 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: 1, totalSteps: 5)

                    Spacer()

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

                OnboardingValuePropsContent(onContinue: onContinue)
            }
        }
    }
}

// MARK: - Preview

#Preview {
    OnboardingValuePropsContent(onContinue: {})
}
