<template>
    <div class="onboarding-carousel">
        <!-- Progress Header -->
        <header class="onboarding-header">
            <div class="progress-container">
                <div class="progress-bar">
                    <div class="progress-fill" :style="{ width: `${progressPercentage}%` }"></div>
                </div>
                <span class="progress-text">{{ currentStep + 1 }} of {{ steps.length }}</span>
            </div>
            <Button variant="ghost" size="sm" @click="$emit('close')" class="skip-button">
                Skip Setup
            </Button>
        </header>

        <!-- Step Content -->
        <main class="onboarding-content">
            <!-- Step 1: Welcome & Profile -->
            <div v-if="currentStep === 0" class="onboarding-step welcome-step">
                <div class="step-hero">
                    <div class="hero-icon">
                        <BaseIcon name="heroicons:home-modern" class="w-16 h-16 text-primary-500" />
                    </div>
                    <Heading :level="2" class="hero-title">Welcome to Your Household Hub!</Heading>
                    <p class="hero-subtitle">Let's get your household organized in under 60 seconds.</p>
                </div>

                <div class="profile-setup">
                    <Card variant="soft" color="primary" class="profile-card">
                        <div class="profile-header">
                            <BaseIcon name="heroicons:user-circle" />
                            <h3>Set Up Your Profile</h3>
                        </div>

                        <div class="profile-form">
                            <div class="avatar-section">
                                <div class="avatar-preview" :class="{ 'has-image': profileImage }">
                                    <img v-if="profileImage" :src="profileImage" alt="Profile" class="avatar-image" />
                                    <BaseIcon v-else name="heroicons:user" class="avatar-placeholder" />
                                </div>
                                <Button variant="outline" size="sm" @click="uploadAvatar">
                                    <BaseIcon name="heroicons:camera" />
                                    Add Photo
                                </Button>
                                <input type="file" ref="avatarInput" @change="handleAvatarUpload" accept="image/*"
                                    hidden />
                            </div>

                            <div class="form-fields">
                                <Input v-model="form.name" label="Your Name" placeholder="What should we call you?"
                                    class="name-input" />
                                <div class="auto-import" v-if="oauthData">
                                    <span class="import-label">Auto-imported from {{ oauthData.provider }}</span>
                                    <Button variant="ghost" size="sm" @click="clearOAuthData">
                                        <BaseIcon name="heroicons:x-mark" />
                                    </Button>
                                </div>
                            </div>
                        </div>
                    </Card>
                </div>
            </div>

            <!-- Step 2: Household Decision -->
            <div v-if="currentStep === 1" class="onboarding-step household-step">
                <div class="step-hero">
                    <Heading :level="2" class="hero-title">Join or Create a Household?</Heading>
                    <p class="hero-subtitle">Choose how you'd like to get started with household management.</p>
                </div>

                <div class="household-options">
                    <div class="option-cards">
                        <Card class="option-card" :class="{ 'option-selected': householdChoice === 'join' }"
                            @click="householdChoice = 'join'">
                            <div class="option-content">
                                <div class="option-icon">
                                    <BaseIcon name="heroicons:user-plus" class="w-12 h-12 text-success-500" />
                                </div>
                                <div class="option-details">
                                    <h3 class="option-title">Join Existing Household</h3>
                                    <p class="option-description">Someone already set up your household? Join with an
                                        invite code.</p>
                                    <div class="option-benefits">
                                        <div class="benefit-item">
                                            <BaseIcon name="heroicons:check-circle" class="benefit-icon" />
                                            <span>Quick setup</span>
                                        </div>
                                        <div class="benefit-item">
                                            <BaseIcon name="heroicons:check-circle" class="benefit-icon" />
                                            <span>Existing data preserved</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="option-radio">
                                    <div class="radio-dot" :class="{ 'radio-selected': householdChoice === 'join' }">
                                    </div>
                                </div>
                            </div>
                        </Card>

                        <Card class="option-card" :class="{ 'option-selected': householdChoice === 'create' }"
                            @click="householdChoice = 'create'">
                            <div class="option-content">
                                <div class="option-icon">
                                    <BaseIcon name="heroicons:plus-circle" class="w-12 h-12 text-primary-500" />
                                </div>
                                <div class="option-details">
                                    <h3 class="option-title">Create New Household</h3>
                                    <p class="option-description">Start fresh with a new household that you can invite
                                        others to join.</p>
                                    <div class="option-benefits">
                                        <div class="benefit-item">
                                            <BaseIcon name="heroicons:check-circle" class="benefit-icon" />
                                            <span>Full control</span>
                                        </div>
                                        <div class="benefit-item">
                                            <BaseIcon name="heroicons:check-circle" class="benefit-icon" />
                                            <span>Customize everything</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="option-radio">
                                    <div class="radio-dot" :class="{ 'radio-selected': householdChoice === 'create' }">
                                    </div>
                                </div>
                            </div>
                        </Card>
                    </div>

                    <!-- Invite Code Input (if joining) -->
                    <div v-if="householdChoice === 'join'" class="invite-section">
                        <Card variant="soft" color="success" class="invite-card">
                            <div class="invite-header">
                                <BaseIcon name="heroicons:key" />
                                <h4>Enter Invite Code</h4>
                            </div>
                            <div class="invite-input-section">
                                <Input v-model="inviteCode" label="Invite Code" placeholder="XXXX-XXXX-XXXX"
                                    class="invite-input" @input="formatInviteCode" />
                                <Button variant="outline" @click="scanQRCode" class="qr-scan-button">
                                    <BaseIcon name="heroicons:qr-code" />
                                    Scan QR
                                </Button>
                            </div>
                            <p class="invite-help">Ask your household member for the invite code or QR code.</p>
                        </Card>
                    </div>

                    <!-- Household Name Input (if creating) -->
                    <div v-if="householdChoice === 'create'" class="household-name-section">
                        <Card variant="soft" color="primary" class="household-card">
                            <div class="household-header">
                                <BaseIcon name="heroicons:home" />
                                <h4>Name Your Household</h4>
                            </div>
                            <Input v-model="householdName" label="Household Name"
                                placeholder="e.g., The Smith Family, Apartment 4B..." class="household-input" />
                            <p class="household-help">Choose a name that everyone in your household will recognize.</p>
                        </Card>
                    </div>
                </div>
            </div>

            <!-- Step 3: Feature Showcase -->
            <div v-if="currentStep === 2" class="onboarding-step features-step">
                <div class="step-hero">
                    <Heading :level="2" class="hero-title">Here's What You Can Do</Heading>
                    <p class="hero-subtitle">A quick tour of features that will transform your household management.</p>
                </div>

                <div class="features-grid">
                    <Card v-for="feature in features" :key="feature.id" class="feature-card" variant="soft"
                        :color="feature.color">
                        <div class="feature-content">
                            <div class="feature-icon">
                                <BaseIcon :name="feature.icon" class="w-8 h-8" />
                            </div>
                            <div class="feature-details">
                                <h3 class="feature-title">{{ feature.title }}</h3>
                                <p class="feature-description">{{ feature.description }}</p>
                                <div class="feature-example">
                                    <span class="example-label">Example:</span>
                                    <span class="example-text">{{ feature.example }}</span>
                                </div>
                            </div>
                        </div>
                    </Card>
                </div>

                <div class="features-footer">
                    <Card variant="soft" color="warning" class="tip-card">
                        <div class="tip-content">
                            <BaseIcon name="heroicons:light-bulb" class="tip-icon" />
                            <div>
                                <h4 class="tip-title">Pro Tip</h4>
                                <p class="tip-text">Start with just one feature - maybe shared shopping lists - and
                                    gradually explore others as your household gets comfortable.</p>
                            </div>
                        </div>
                    </Card>
                </div>
            </div>

            <!-- Step 4: Setup Complete -->
            <div v-if="currentStep === 3" class="onboarding-step complete-step">
                <div class="completion-hero">
                    <div class="success-animation">
                        <BaseIcon name="heroicons:check-circle" class="success-icon" />
                    </div>
                    <Heading :level="2" class="completion-title">You're All Set!</Heading>
                    <p class="completion-subtitle">Your household management hub is ready to use.</p>
                </div>

                <div class="next-steps">
                    <Card variant="soft" color="success" class="next-steps-card">
                        <div class="next-steps-header">
                            <BaseIcon name="heroicons:rocket-launch" />
                            <h3>Recommended First Steps</h3>
                        </div>

                        <div class="next-steps-list">
                            <div v-for="step in nextSteps" :key="step.id" class="next-step-item">
                                <div class="step-number">{{ step.id }}</div>
                                <div class="step-content">
                                    <span class="step-title">{{ step.title }}</span>
                                    <span class="step-time">{{ step.time }}</span>
                                </div>
                                <BaseIcon name="heroicons:arrow-right" class="step-arrow" />
                            </div>
                        </div>
                    </Card>

                    <div class="completion-actions">
                        <Button @click="goToDashboard" size="lg" class="dashboard-button">
                            <template #icon-left>
                                <BaseIcon name="heroicons:home" />
                            </template>
                            Go to Dashboard
                        </Button>

                        <Button variant="outline" @click="inviteMembers" size="lg" class="invite-button">
                            <template #icon-left>
                                <BaseIcon name="heroicons:user-plus" />
                            </template>
                            Invite Household Members
                        </Button>
                    </div>
                </div>
            </div>
        </main>

        <!-- Navigation Footer -->
        <footer class="onboarding-footer">
            <div class="footer-actions">
                <Button v-if="currentStep > 0" variant="outline" @click="prevStep" :disabled="processing"
                    class="back-button">
                    <template #icon-left>
                        <BaseIcon name="heroicons:arrow-left" />
                    </template>
                    Back
                </Button>

                <div class="spacer"></div>

                <Button v-if="currentStep < steps.length - 1" @click="nextStep" :disabled="!canProceed"
                    :loading="processing" size="lg" class="next-button">
                    {{ getNextButtonText() }}
                    <template #icon-right>
                        <BaseIcon name="heroicons:arrow-right" />
                    </template>
                </Button>
            </div>
        </footer>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { Heading, Button, Card, Input } from '@/components/ui'
import BaseIcon from '@/components/BaseIcon.vue'
import { useAuthStore } from '@/stores/auth'
import { useGroupStore } from '@/stores/groupStore'
import { useNotificationStore } from '@/stores/notifications'

interface Step {
    id: string
    title: string
    canSkip: boolean
}

interface Feature {
    id: string
    title: string
    description: string
    example: string
    icon: string
    color: 'primary' | 'success' | 'warning' | 'error'
}

interface NextStep {
    id: number
    title: string
    time: string
}

const emit = defineEmits<{
    close: []
    complete: [householdId?: number]
}>()

const router = useRouter()
const auth = useAuthStore()
const groupStore = useGroupStore()
const notifications = useNotificationStore()

// Steps configuration
const steps: Step[] = [
    { id: 'profile', title: 'Profile Setup', canSkip: false },
    { id: 'household', title: 'Household Choice', canSkip: false },
    { id: 'features', title: 'Feature Tour', canSkip: true },
    { id: 'complete', title: 'Setup Complete', canSkip: false }
]

// Current state
const currentStep = ref(0)
const processing = ref(false)

// Form data
const form = ref({
    name: auth.user?.name || ''
})

const profileImage = ref<string | null>(auth.user?.avatarUrl || null)
const avatarInput = ref<HTMLInputElement>()

// OAuth data (simulated - would come from actual OAuth flow)
const oauthData = ref<{ provider: string; name: string; image?: string } | null>(
    auth.user ? { provider: 'Google', name: auth.user.name } : null
)

// Household setup
const householdChoice = ref<'join' | 'create' | ''>('')
const inviteCode = ref('')
const householdName = ref('')

// Features showcase
const features: Feature[] = [
    {
        id: 'chores',
        title: 'Smart Chore Management',
        description: 'Fair assignment, automatic rotation, and point-based rewards keep everyone motivated.',
        example: '"Take out trash" auto-assigned to Jake, due tomorrow',
        icon: 'heroicons:clipboard-document-check',
        color: 'primary'
    },
    {
        id: 'shopping',
        title: 'Collaborative Shopping',
        description: 'Real-time shared lists prevent duplicate purchases and ensure nothing is forgotten.',
        example: 'Sarah adds "Milk" → Jake sees it instantly at the store',
        icon: 'heroicons:shopping-cart',
        color: 'success'
    },
    {
        id: 'expenses',
        title: 'Automatic Bill Splitting',
        description: 'Snap receipts, split fairly, and settle debts with built-in payment tracking.',
        example: 'Dinner receipt: $60 → Auto-split 3 ways = $20 each',
        icon: 'heroicons:receipt-percent',
        color: 'warning'
    },
    {
        id: 'activity',
        title: 'Household Activity Feed',
        description: 'Stay connected with real-time updates on completed tasks and shared expenses.',
        example: 'Alex completed "Clean kitchen" +15 points!',
        icon: 'heroicons:bell',
        color: 'error'
    }
]

// Next steps recommendations
const nextSteps: NextStep[] = [
    { id: 1, title: 'Add your first shared shopping list', time: '2 min' },
    { id: 2, title: 'Set up recurring household chores', time: '5 min' },
    { id: 3, title: 'Invite other household members', time: '1 min' }
]

// Computed properties
const progressPercentage = computed(() => {
    return ((currentStep.value + 1) / steps.length) * 100
})

const canProceed = computed(() => {
    switch (currentStep.value) {
        case 0: // Profile setup
            return form.value.name.trim().length > 0
        case 1: // Household choice
            if (householdChoice.value === 'join') {
                return inviteCode.value.trim().length >= 12 // Basic validation
            }
            if (householdChoice.value === 'create') {
                return householdName.value.trim().length > 0
            }
            return householdChoice.value !== ''
        case 2: // Features (can always proceed)
            return true
        case 3: // Complete (no next step)
            return false
        default:
            return false
    }
})

// Methods
function nextStep() {
    if (currentStep.value < steps.length - 1) {
        if (currentStep.value === 1) {
            // Process household setup before moving to features
            processHouseholdSetup()
        } else {
            currentStep.value++
        }
    }
}

function prevStep() {
    if (currentStep.value > 0) {
        currentStep.value--
    }
}

function getNextButtonText() {
    switch (currentStep.value) {
        case 0:
            return 'Continue'
        case 1:
            return householdChoice.value === 'join' ? 'Join Household' : 'Create Household'
        case 2:
            return 'Finish Setup'
        default:
            return 'Next'
    }
}

async function processHouseholdSetup() {
    processing.value = true
    try {
        if (householdChoice.value === 'join') {
            await joinHousehold()
        } else if (householdChoice.value === 'create') {
            await createHousehold()
        }
        currentStep.value++
    } catch (error) {
        notifications.addNotification({
            type: 'error',
            message: 'Failed to set up household. Please try again.'
        })
    } finally {
        processing.value = false
    }
}

async function joinHousehold() {
    // API call to join household with invite code
    const cleanCode = inviteCode.value.replace(/[-\s]/g, '')
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 1000))
    notifications.addNotification({
        type: 'success',
        message: 'Successfully joined household!'
    })
}

async function createHousehold() {
    // API call to create new household
    const householdData = {
        name: householdName.value.trim(),
        created_by: auth.user?.id
    }
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 1000))
    notifications.addNotification({
        type: 'success',
        message: `Created "${householdName.value}" household!`
    })
}

function uploadAvatar() {
    avatarInput.value?.click()
}

function handleAvatarUpload(event: Event) {
    const file = (event.target as HTMLInputElement).files?.[0]
    if (file) {
        const reader = new FileReader()
        reader.onload = (e) => {
            profileImage.value = e.target?.result as string
        }
        reader.readAsDataURL(file)
    }
}

function clearOAuthData() {
    oauthData.value = null
    form.value.name = ''
}

function formatInviteCode(event: Event) {
    const input = event.target as HTMLInputElement
    let value = input.value.replace(/[^A-Z0-9]/gi, '').toUpperCase()

    // Format as XXXX-XXXX-XXXX
    if (value.length > 0) {
        value = value.match(/.{1,4}/g)?.join('-') || value
        if (value.length > 14) {
            value = value.substring(0, 14)
        }
    }

    inviteCode.value = value
    nextTick(() => {
        input.value = value
    })
}

function scanQRCode() {
    // Would implement QR code scanning here
    notifications.addNotification({
        type: 'info',
        message: 'QR code scanning would open camera interface'
    })
}

function goToDashboard() {
    router.push('/')
    emit('complete')
}

function inviteMembers() {
    router.push('/household/settings')
    emit('complete')
}
</script>

<style scoped>
.onboarding-carousel {
    @apply bg-surface-primary rounded-lg w-full max-w-4xl max-h-[90vh] overflow-hidden flex flex-col;
}

/* Header */
.onboarding-header {
    @apply flex items-center justify-between p-6 border-b border-border-primary bg-surface-soft;
}

.progress-container {
    @apply flex items-center gap-4 flex-1;
}

.progress-bar {
    @apply w-64 h-2 bg-border-secondary rounded-full overflow-hidden;
}

.progress-fill {
    @apply h-full bg-primary-500 transition-all duration-300 ease-out;
}

.progress-text {
    @apply text-sm font-medium text-text-secondary;
}

.skip-button {
    @apply text-text-tertiary hover:text-text-secondary;
}

/* Content */
.onboarding-content {
    @apply flex-1 overflow-y-auto p-8;
}

.onboarding-step {
    @apply max-w-3xl mx-auto space-y-8;
}

/* Step Hero */
.step-hero {
    @apply text-center space-y-4;
}

.hero-icon {
    @apply flex justify-center mb-6;
}

.hero-title {
    @apply text-3xl font-bold text-text-primary;
}

.hero-subtitle {
    @apply text-lg text-text-secondary max-w-2xl mx-auto;
}

/* Welcome Step */
.profile-card {
    @apply p-6;
}

.profile-header {
    @apply flex items-center gap-3 mb-6;
}

.profile-header h3 {
    @apply text-xl font-semibold text-text-primary;
}

.profile-form {
    @apply flex flex-col md:flex-row gap-6 items-start;
}

.avatar-section {
    @apply flex flex-col items-center gap-3;
}

.avatar-preview {
    @apply w-24 h-24 rounded-full border-2 border-border-secondary overflow-hidden flex items-center justify-center;
    @apply bg-surface-secondary;
}

.has-image {
    @apply border-primary-300;
}

.avatar-image {
    @apply w-full h-full object-cover;
}

.avatar-placeholder {
    @apply w-12 h-12 text-text-tertiary;
}

.form-fields {
    @apply flex-1 space-y-4;
}

.name-input {
    @apply w-full;
}

.auto-import {
    @apply flex items-center gap-2 text-sm text-success-600 bg-success-50 dark:bg-success-950/20 px-3 py-2 rounded-md;
}

/* Household Step */
.household-options {
    @apply space-y-6;
}

.option-cards {
    @apply grid grid-cols-1 md:grid-cols-2 gap-6;
}

.option-card {
    @apply cursor-pointer transition-all duration-200 hover:border-primary-300;
}

.option-selected {
    @apply border-primary-500 bg-primary-50 dark:bg-primary-950/20;
}

.option-content {
    @apply p-6 flex flex-col items-center text-center space-y-4 relative;
}

.option-icon {
    @apply mb-2;
}

.option-details {
    @apply space-y-3;
}

.option-title {
    @apply text-xl font-semibold text-text-primary;
}

.option-description {
    @apply text-text-secondary;
}

.option-benefits {
    @apply space-y-2;
}

.benefit-item {
    @apply flex items-center gap-2 text-sm text-success-600;
}

.benefit-icon {
    @apply w-4 h-4;
}

.option-radio {
    @apply absolute top-4 right-4 w-6 h-6 rounded-full border-2 border-border-secondary flex items-center justify-center;
}

.radio-dot {
    @apply w-3 h-3 rounded-full bg-transparent transition-colors duration-200;
}

.option-selected .option-radio {
    @apply border-primary-500;
}

.option-selected .radio-dot {
    @apply bg-primary-500;
}

/* Invite Section */
.invite-section,
.household-name-section {
    @apply max-w-md mx-auto;
}

.invite-card,
.household-card {
    @apply p-6;
}

.invite-header,
.household-header {
    @apply flex items-center gap-3 mb-4;
}

.invite-header h4,
.household-header h4 {
    @apply text-lg font-semibold text-text-primary;
}

.invite-input-section {
    @apply flex gap-3 mb-3;
}

.invite-input {
    @apply flex-1;
}

.qr-scan-button {
    @apply shrink-0;
}

.invite-help,
.household-help {
    @apply text-sm text-text-secondary;
}

/* Features Step */
.features-grid {
    @apply grid grid-cols-1 md:grid-cols-2 gap-6;
}

.feature-card {
    @apply p-6;
}

.feature-content {
    @apply flex gap-4;
}

.feature-icon {
    @apply shrink-0;
}

.feature-details {
    @apply space-y-3;
}

.feature-title {
    @apply text-lg font-semibold text-text-primary;
}

.feature-description {
    @apply text-text-secondary;
}

.feature-example {
    @apply space-y-1;
}

.example-label {
    @apply text-xs font-medium text-text-tertiary uppercase tracking-wide;
}

.example-text {
    @apply text-sm font-mono text-text-secondary bg-surface-secondary px-2 py-1 rounded;
}

.features-footer {
    @apply mt-8;
}

.tip-card {
    @apply p-4;
}

.tip-content {
    @apply flex gap-3;
}

.tip-icon {
    @apply w-6 h-6 text-warning-500 shrink-0;
}

.tip-title {
    @apply font-semibold text-text-primary mb-1;
}

.tip-text {
    @apply text-sm text-text-secondary;
}

/* Complete Step */
.completion-hero {
    @apply text-center space-y-6;
}

.success-animation {
    @apply flex justify-center;
}

.success-icon {
    @apply w-20 h-20 text-success-500 animate-pulse;
}

.completion-title {
    @apply text-3xl font-bold text-text-primary;
}

.completion-subtitle {
    @apply text-lg text-text-secondary;
}

.next-steps {
    @apply space-y-6;
}

.next-steps-card {
    @apply p-6;
}

.next-steps-header {
    @apply flex items-center gap-3 mb-6;
}

.next-steps-header h3 {
    @apply text-xl font-semibold text-text-primary;
}

.next-steps-list {
    @apply space-y-4;
}

.next-step-item {
    @apply flex items-center gap-4 p-4 bg-surface-primary rounded-lg;
}

.step-number {
    @apply w-8 h-8 bg-success-500 text-white rounded-full flex items-center justify-center font-bold text-sm;
}

.step-content {
    @apply flex-1 flex flex-col gap-1;
}

.step-title {
    @apply font-medium text-text-primary;
}

.step-time {
    @apply text-sm text-text-secondary;
}

.step-arrow {
    @apply w-5 h-5 text-text-tertiary;
}

.completion-actions {
    @apply flex flex-col sm:flex-row gap-4 justify-center;
}

/* Footer */
.onboarding-footer {
    @apply p-6 border-t border-border-primary bg-surface-soft;
}

.footer-actions {
    @apply flex items-center;
}

.spacer {
    @apply flex-1;
}

.next-button {
    @apply min-w-[140px];
}
</style>