package com.tt.honeyDue.ui.screens.onboarding

import androidx.compose.animation.*
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.ui.theme.*
import com.tt.honeyDue.viewmodel.OnboardingStep
import com.tt.honeyDue.viewmodel.OnboardingViewModel
import com.tt.honeyDue.viewmodel.OnboardingIntent

@OptIn(ExperimentalAnimationApi::class)
@Composable
fun OnboardingScreen(
    onComplete: () -> Unit,
    onLoginSuccess: (Boolean) -> Unit, // Boolean = isVerified
    viewModel: OnboardingViewModel = viewModel { OnboardingViewModel() }
) {
    val currentStep by viewModel.currentStep.collectAsStateWithLifecycle()
    val userIntent by viewModel.userIntent.collectAsStateWithLifecycle()
    val isComplete by viewModel.isComplete.collectAsStateWithLifecycle()

    // Handle onboarding completion
    LaunchedEffect(isComplete) {
        if (isComplete) {
            onComplete()
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background)
    ) {
        // Navigation bar (shared across all steps)
        OnboardingNavigationBar(
            currentStep = currentStep,
            userIntent = userIntent,
            onBack = { viewModel.previousStep() },
            onSkip = { viewModel.skipStep() }
        )

        // Content area with animated transitions
        Box(
            modifier = Modifier
                .fillMaxSize()
                .weight(1f)
        ) {
            AnimatedContent(
                targetState = currentStep,
                transitionSpec = {
                    if (targetState.ordinal > initialState.ordinal) {
                        // Moving forward - slide from right
                        slideInHorizontally { width -> width } + fadeIn() togetherWith
                            slideOutHorizontally { width -> -width } + fadeOut()
                    } else {
                        // Moving back - slide from left
                        slideInHorizontally { width -> -width } + fadeIn() togetherWith
                            slideOutHorizontally { width -> width } + fadeOut()
                    }.using(SizeTransform(clip = false))
                },
                label = "onboarding_content"
            ) { step ->
                when (step) {
                    OnboardingStep.WELCOME -> OnboardingWelcomeContent(
                        onStartFresh = {
                            viewModel.setUserIntent(OnboardingIntent.START_FRESH)
                            viewModel.nextStep()
                        },
                        onJoinExisting = {
                            viewModel.setUserIntent(OnboardingIntent.JOIN_EXISTING)
                            viewModel.nextStep()
                        },
                        onLogin = { isVerified ->
                            onLoginSuccess(isVerified)
                        }
                    )

                    OnboardingStep.VALUE_PROPS -> OnboardingValuePropsContent(
                        onContinue = { viewModel.nextStep() }
                    )

                    OnboardingStep.NAME_RESIDENCE -> OnboardingNameResidenceContent(
                        viewModel = viewModel,
                        onContinue = { viewModel.nextStep() }
                    )

                    OnboardingStep.CREATE_ACCOUNT -> OnboardingCreateAccountContent(
                        viewModel = viewModel,
                        onAccountCreated = { isVerified ->
                            if (isVerified) {
                                // Skip email verification
                                if (userIntent == OnboardingIntent.JOIN_EXISTING) {
                                    viewModel.goToStep(OnboardingStep.JOIN_RESIDENCE)
                                } else {
                                    viewModel.goToStep(OnboardingStep.HOME_PROFILE)
                                }
                            } else {
                                viewModel.nextStep()
                            }
                        }
                    )

                    OnboardingStep.VERIFY_EMAIL -> OnboardingVerifyEmailContent(
                        viewModel = viewModel,
                        onVerified = {
                            if (userIntent == OnboardingIntent.JOIN_EXISTING) {
                                viewModel.goToStep(OnboardingStep.JOIN_RESIDENCE)
                            } else {
                                viewModel.goToStep(OnboardingStep.HOME_PROFILE)
                            }
                        }
                    )

                    OnboardingStep.JOIN_RESIDENCE -> OnboardingJoinResidenceContent(
                        viewModel = viewModel,
                        onJoined = { viewModel.completeOnboarding() }
                    )

                    OnboardingStep.RESIDENCE_LOCATION -> {
                        // Location step removed — skip to home profile if we land here
                        LaunchedEffect(Unit) { viewModel.goToStep(OnboardingStep.HOME_PROFILE) }
                    }

                    OnboardingStep.HOME_PROFILE -> OnboardingHomeProfileContent(
                        viewModel = viewModel,
                        onContinue = {
                            viewModel.createResidence()
                            viewModel.nextStep()
                        },
                        onSkip = {
                            viewModel.createResidence()
                            viewModel.skipStep()
                        }
                    )

                    OnboardingStep.FIRST_TASK -> OnboardingFirstTaskContent(
                        viewModel = viewModel,
                        onTasksAdded = { viewModel.completeOnboarding() }
                    )

                    OnboardingStep.SUBSCRIPTION_UPSELL -> {
                        // Subscription removed from onboarding — app is free
                        LaunchedEffect(Unit) { viewModel.completeOnboarding() }
                    }
                }
            }
        }
    }
}

@Composable
private fun OnboardingNavigationBar(
    currentStep: OnboardingStep,
    userIntent: OnboardingIntent,
    onBack: () -> Unit,
    onSkip: () -> Unit
) {
    val showBackButton = when (currentStep) {
        OnboardingStep.WELCOME,
        OnboardingStep.JOIN_RESIDENCE,
        OnboardingStep.RESIDENCE_LOCATION,
        OnboardingStep.HOME_PROFILE,
        OnboardingStep.FIRST_TASK,
        OnboardingStep.SUBSCRIPTION_UPSELL -> false
        else -> true
    }

    val showSkipButton = when (currentStep) {
        OnboardingStep.VALUE_PROPS,
        OnboardingStep.JOIN_RESIDENCE,
        OnboardingStep.HOME_PROFILE,
        OnboardingStep.FIRST_TASK,
        OnboardingStep.SUBSCRIPTION_UPSELL -> true
        else -> false
    }

    val showProgressIndicator = when (currentStep) {
        OnboardingStep.WELCOME,
        OnboardingStep.JOIN_RESIDENCE,
        OnboardingStep.RESIDENCE_LOCATION,
        OnboardingStep.HOME_PROFILE,
        OnboardingStep.FIRST_TASK,
        OnboardingStep.SUBSCRIPTION_UPSELL -> false
        else -> true
    }

    val currentProgressStep = when (currentStep) {
        OnboardingStep.WELCOME -> 0
        OnboardingStep.VALUE_PROPS -> 1
        OnboardingStep.NAME_RESIDENCE -> 2
        OnboardingStep.CREATE_ACCOUNT -> 3
        OnboardingStep.VERIFY_EMAIL -> 4
        OnboardingStep.JOIN_RESIDENCE -> 4
        OnboardingStep.RESIDENCE_LOCATION -> 4
        OnboardingStep.HOME_PROFILE -> 4
        OnboardingStep.FIRST_TASK -> 4
        OnboardingStep.SUBSCRIPTION_UPSELL -> 4
    }

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = OrganicSpacing.lg, vertical = OrganicSpacing.md),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // Back button
        Box(modifier = Modifier.width(48.dp)) {
            if (showBackButton) {
                IconButton(onClick = onBack) {
                    Icon(
                        Icons.AutoMirrored.Filled.ArrowBack,
                        contentDescription = "Back",
                        tint = MaterialTheme.colorScheme.primary
                    )
                }
            }
        }

        // Progress indicator
        Box(
            modifier = Modifier.weight(1f),
            contentAlignment = Alignment.Center
        ) {
            if (showProgressIndicator) {
                OnboardingProgressIndicator(
                    currentStep = currentProgressStep,
                    totalSteps = 5
                )
            }
        }

        // Skip button
        Box(modifier = Modifier.width(48.dp)) {
            if (showSkipButton) {
                TextButton(onClick = onSkip) {
                    Text(
                        "Skip",
                        style = MaterialTheme.typography.bodyMedium,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        }
    }
}

@Composable
fun OnboardingProgressIndicator(
    currentStep: Int,
    totalSteps: Int
) {
    Row(
        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.xs),
        verticalAlignment = Alignment.CenterVertically
    ) {
        repeat(totalSteps) { index ->
            Box(
                modifier = Modifier
                    .size(8.dp)
                    .clip(CircleShape)
                    .background(
                        if (index <= currentStep) {
                            MaterialTheme.colorScheme.primary
                        } else {
                            MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.3f)
                        }
                    )
            )
        }
    }
}
