<template>
    <Dialog v-model="isOpen" :unmount="false">
        <div class="auth-sheet">
            <!-- Header -->
            <div class="auth-header">
                <div class="brand">
                    <h1 class="brand-title">mitlist</h1>
                    <p class="brand-subtitle">Smart household management</p>
                </div>

                <button v-if="allowClose" @click="closeSheet" class="close-button" aria-label="Close authentication">
                    <span class="material-icons">close</span>
                </button>
            </div>

            <!-- Mode Toggle -->
            <div class="mode-toggle">
                <div class="mode-buttons">
                    <button :class="['mode-btn', { active: mode === 'login' }]" @click="setMode('login')">
                        Sign In
                    </button>
                    <button :class="['mode-btn', { active: mode === 'register' }]" @click="setMode('register')">
                        Get Started
                    </button>
                </div>
            </div>

            <!-- Content -->
            <div class="auth-content">
                <!-- Welcome Message -->
                <div class="welcome-section">
                    <h2 class="welcome-title">
                        {{ mode === 'login' ? 'Welcome back!' : 'Welcome to mitlist!' }}
                    </h2>
                    <p class="welcome-text">
                        {{
                            mode === 'login'
                                ? 'Sign in to your household dashboard'
                                : 'Join thousands of organized households'
                        }}
                    </p>
                </div>

                <!-- Demo Mode Banner -->
                <div v-if="showDemoMode" class="demo-banner">
                    <div class="demo-content">
                        <span class="material-icons demo-icon">play_circle</span>
                        <div>
                            <h3 class="demo-title">Try Demo Mode</h3>
                            <p class="demo-text">Explore without creating an account</p>
                        </div>
                    </div>
                    <Button variant="soft" color="primary" size="sm" @click="startDemo">
                        Try Demo
                    </Button>
                </div>

                <!-- Social Auth (Primary) -->
                <div class="social-auth-section">
                    <div class="social-buttons">
                        <Button v-for="provider in socialProviders" :key="provider.id" variant="outline" color="neutral"
                            size="lg" fullWidth :loading="authState.loading === provider.id"
                            @click="handleSocialAuth(provider)" class="social-btn">
                            <template #icon-left>
                                <img :src="provider.icon" :alt="provider.name" class="social-icon" />
                            </template>
                            {{ mode === 'login' ? 'Continue' : 'Sign up' }} with {{ provider.name }}
                        </Button>
                    </div>
                </div>

                <!-- Divider -->
                <div class="divider">
                    <span class="divider-text">or continue with email</span>
                </div>

                <!-- Email Form -->
                <form @submit.prevent="handleEmailAuth" class="email-form">
                    <div class="form-field">
                        <Input v-model="authState.email" type="email" placeholder="Enter your email"
                            :error="authState.errors.email" :loading="authState.loading === 'email'"
                            @input="validateEmail" @blur="validateEmail" required autofocus />
                    </div>

                    <div v-if="emailMode === 'password'" class="form-field">
                        <Input v-model="authState.password" type="password" placeholder="Enter your password"
                            :error="authState.errors.password" @input="validatePassword" @blur="validatePassword"
                            required />
                    </div>

                    <div v-if="mode === 'register' && emailMode === 'password'" class="form-field">
                        <Input v-model="authState.name" type="text" placeholder="Your name"
                            :error="authState.errors.name" @input="validateName" @blur="validateName" required />
                    </div>

                    <!-- Magic Link Info -->
                    <div v-if="emailMode === 'magic'" class="magic-info">
                        <div class="magic-icon">
                            <span class="material-icons">magic_button</span>
                        </div>
                        <div class="magic-text">
                            <h4>Sign in with magic link</h4>
                            <p>We'll send a secure sign-in link to your email</p>
                        </div>
                    </div>

                    <!-- Submit Button -->
                    <Button type="submit" variant="solid" color="primary" size="lg" fullWidth
                        :loading="authState.loading === 'email'" :disabled="!isFormValid">
                        {{
                            emailMode === 'magic'
                                ? 'Send Magic Link'
                                : mode === 'login'
                                    ? 'Sign In'
                                    : 'Create Account'
                        }}
                    </Button>

                    <!-- Auth Mode Toggle -->
                    <div class="auth-toggle">
                        <button type="button" @click="toggleEmailMode" class="toggle-link">
                            {{
                                emailMode === 'magic'
                                    ? 'Use password instead'
                                    : 'Use magic link instead'
                            }}
                        </button>
                    </div>
                </form>

                <!-- Footer -->
                <div class="auth-footer">
                    <p class="terms-text">
                        By continuing, you agree to our
                        <a href="/terms" class="terms-link">Terms of Service</a>
                        and
                        <a href="/privacy" class="terms-link">Privacy Policy</a>
                    </p>
                </div>
            </div>
        </div>
    </Dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useNotificationStore } from '@/stores/notifications'
import Dialog from '@/components/ui/Dialog.vue'
import Button from '@/components/ui/Button.vue'
import Input from '@/components/ui/Input.vue'

interface SocialProvider {
    id: string
    name: string
    icon: string
    url: string
}

interface AuthState {
    email: string
    password: string
    name: string
    loading: string | null
    errors: {
        email?: string
        password?: string
        name?: string
        general?: string
    }
}

const props = defineProps<{
    modelValue: boolean
    allowClose?: boolean
    showDemoMode?: boolean
    initialMode?: 'login' | 'register'
}>()

const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    'demo-started': []
    'auth-success': [user: any]
}>()

const router = useRouter()
const authStore = useAuthStore()
const notificationStore = useNotificationStore()

const isOpen = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
})

const mode = ref<'login' | 'register'>(props.initialMode || 'login')
const emailMode = ref<'password' | 'magic'>('magic') // Default to magic link

const authState = ref<AuthState>({
    email: '',
    password: '',
    name: '',
    loading: null,
    errors: {}
})

// Social providers in order of preference
const socialProviders = ref<SocialProvider[]>([
    {
        id: 'google',
        name: 'Google',
        icon: 'https://developers.google.com/identity/images/g-logo.png',
        url: '/api/auth/google'
    },
    {
        id: 'apple',
        name: 'Apple',
        icon: 'https://appleid.apple.com/favicon.ico',
        url: '/api/auth/apple'
    }
])

// Auto-detect returning users
onMounted(() => {
    const lastEmail = localStorage.getItem('last-email')
    if (lastEmail) {
        authState.value.email = lastEmail
        mode.value = 'login'
    }
})

const setMode = (newMode: 'login' | 'register') => {
    mode.value = newMode
    clearErrors()
}

const closeSheet = () => {
    if (props.allowClose) {
        isOpen.value = false
    }
}

const startDemo = () => {
    emit('demo-started')
    notificationStore.addNotification({
        type: 'success',
        message: 'Demo mode started! Explore all features.',
    })
    closeSheet()
}

const toggleEmailMode = () => {
    emailMode.value = emailMode.value === 'magic' ? 'password' : 'magic'
    clearErrors()
}

const clearErrors = () => {
    authState.value.errors = {}
}

// Validation functions
const validateEmail = () => {
    const email = authState.value.email
    if (!email) {
        authState.value.errors.email = 'Email is required'
        return false
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(email)) {
        authState.value.errors.email = 'Please enter a valid email'
        return false
    }

    delete authState.value.errors.email
    return true
}

const validatePassword = () => {
    const password = authState.value.password
    if (emailMode.value === 'magic') return true

    if (!password) {
        authState.value.errors.password = 'Password is required'
        return false
    }

    if (password.length < 8) {
        authState.value.errors.password = 'Password must be at least 8 characters'
        return false
    }

    delete authState.value.errors.password
    return true
}

const validateName = () => {
    const name = authState.value.name
    if (mode.value === 'login' || emailMode.value === 'magic') return true

    if (!name || name.trim().length < 2) {
        authState.value.errors.name = 'Please enter your name'
        return false
    }

    delete authState.value.errors.name
    return true
}

const isFormValid = computed(() => {
    if (emailMode.value === 'magic') {
        return validateEmail()
    }

    if (mode.value === 'register') {
        return validateEmail() && validatePassword() && validateName()
    }

    return validateEmail() && validatePassword()
})

// Auth handlers
const handleSocialAuth = async (provider: SocialProvider) => {
    authState.value.loading = provider.id
    try {
        // In a real app, this would redirect to OAuth provider
        window.location.href = provider.url
    } catch (error) {
        authState.value.errors.general = `Failed to sign in with ${provider.name}`
        authState.value.loading = null
    }
}

const handleEmailAuth = async () => {
    if (!isFormValid.value) return

    authState.value.loading = 'email'
    clearErrors()

    try {
        if (emailMode.value === 'magic') {
            // Send magic link
            await authStore.sendMagicLink(authState.value.email)

            notificationStore.addNotification({
                type: 'success',
                message: 'Magic link sent! Check your email.',
            })

            closeSheet()
        } else {
            // Regular email/password auth
            if (mode.value === 'login') {
                const user = await authStore.login({
                    email: authState.value.email,
                    password: authState.value.password
                })

                localStorage.setItem('last-email', authState.value.email)
                emit('auth-success', user)
                closeSheet()
            } else {
                const user = await authStore.register({
                    email: authState.value.email,
                    password: authState.value.password,
                    name: authState.value.name
                })

                localStorage.setItem('last-email', authState.value.email)
                emit('auth-success', user)
                closeSheet()
            }
        }
    } catch (error: any) {
        authState.value.errors.general = error.message || 'Authentication failed'
    } finally {
        authState.value.loading = null
    }
}

// Clear form when mode changes
watch(mode, () => {
    authState.value.password = ''
    authState.value.name = ''
    clearErrors()
})
</script>

<style scoped>
.auth-sheet {
    @apply max-w-md mx-auto bg-white rounded-2xl shadow-floating p-6;
    @apply max-h-[90vh] overflow-y-auto;
}

.auth-header {
    @apply flex items-start justify-between mb-6;
}

.brand-title {
    @apply text-2xl font-bold text-primary-600 mb-1;
}

.brand-subtitle {
    @apply text-sm text-neutral-600;
}

.close-button {
    @apply p-2 rounded-full text-neutral-400 hover:text-neutral-600 hover:bg-neutral-100;
    @apply transition-colors duration-micro;
}

.mode-toggle {
    @apply mb-6;
}

.mode-buttons {
    @apply flex bg-neutral-100 rounded-lg p-1;
}

.mode-btn {
    @apply flex-1 py-2 px-4 text-sm font-medium rounded-md transition-all duration-micro;
    @apply text-neutral-600 hover:text-neutral-900;
}

.mode-btn.active {
    @apply bg-white text-primary-600 shadow-soft;
}

.welcome-section {
    @apply text-center mb-6;
}

.welcome-title {
    @apply text-xl font-semibold text-neutral-900 mb-2;
}

.welcome-text {
    @apply text-sm text-neutral-600;
}

.demo-banner {
    @apply flex items-center justify-between p-4 bg-primary-50 rounded-lg border border-primary-200 mb-6;
}

.demo-content {
    @apply flex items-center gap-3;
}

.demo-icon {
    @apply text-primary-500 text-xl;
}

.demo-title {
    @apply text-sm font-medium text-primary-900;
}

.demo-text {
    @apply text-xs text-primary-700;
}

.social-auth-section {
    @apply mb-6;
}

.social-buttons {
    @apply space-y-3;
}

.social-btn {
    @apply justify-start;
}

.social-icon {
    @apply w-5 h-5;
}

.divider {
    @apply relative flex items-center justify-center mb-6;
}

.divider::before {
    @apply absolute inset-0 flex items-center;
    content: "";
}

.divider::before {
    @apply border-t border-neutral-200;
}

.divider-text {
    @apply bg-white px-4 text-xs text-neutral-500 font-medium;
}

.email-form {
    @apply space-y-4;
}

.form-field {
    @apply space-y-1;
}

.magic-info {
    @apply flex items-start gap-3 p-4 bg-blue-50 rounded-lg border border-blue-200;
}

.magic-icon {
    @apply text-blue-500 text-xl;
}

.magic-text h4 {
    @apply text-sm font-medium text-blue-900 mb-1;
}

.magic-text p {
    @apply text-xs text-blue-700;
}

.auth-toggle {
    @apply text-center;
}

.toggle-link {
    @apply text-sm text-primary-600 hover:text-primary-700 font-medium;
    @apply transition-colors duration-micro;
}

.auth-footer {
    @apply mt-6 pt-6 border-t border-neutral-200;
}

.terms-text {
    @apply text-xs text-neutral-500 text-center;
}

.terms-link {
    @apply text-primary-600 hover:text-primary-700;
    @apply transition-colors duration-micro;
}

/* Mobile optimizations */
@media (max-width: 640px) {
    .auth-sheet {
        @apply m-4 max-h-[95vh];
    }
}

/* Animation for form transitions */
.form-field {
    animation: fade-in 200ms ease-out;
}

@keyframes fade-in {
    from {
        opacity: 0;
        transform: translateY(10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>