import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { supabase } from '@/supabase'

export const useAuthStore = defineStore('auth', () => {
    const userSession = ref<any>(null)
    const userProfile = ref<any>(null)

    const isAuthenticated = computed(() => !!userSession.value)

    // We check the custom Postgres role we put in our `users` table
    const role = computed(() => userProfile.value?.role || userSession.value?.user?.user_metadata?.role)
    const userName = computed(() => userProfile.value?.full_name || userSession.value?.user?.user_metadata?.full_name)

    const isAdmin = computed(() => role.value?.toUpperCase() === 'ADMIN')
    const isDriver = computed(() => role.value?.toUpperCase() === 'DRIVER')
    const isPromoter = computed(() => role.value?.toUpperCase() === 'PROMOTER')
    const isPassenger = computed(() => !role.value || role.value?.toUpperCase() === 'PASSENGER')

    /** Listens for Supabase Auth state changes */
    supabase.auth.onAuthStateChange(async (event, session) => {
        userSession.value = session

        // Cargar perfil solo en inicio de sesión real, NO en cada token refresh.
        // Cuando la pantalla se apaga y vuelve, Supabase re-emite TOKEN_REFRESHED.
        // Si se re-fetchea el perfil en ese momento, la red puede estar inestable
        // y el fetch queda colgado, dejando userProfile = null y re-disparando
        // todos los watchers de auto_location y autenticación.
        const profileLoadEvents = ['SIGNED_IN', 'INITIAL_SESSION']

        if (session?.user && profileLoadEvents.includes(event)) {
            // Timeout de seguridad: si la red está inestable al despertar,
            // no bloquear indefinidamente
            const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), 10000))
            const profileFetch = (async () => {
                try {
                    const { data } = await supabase
                        .from('users')
                        .select('*')
                        .eq('id', session.user!.id)
                        .single()
                    return data ?? null
                } catch {
                    return null
                }
            })()

            const data = await Promise.race([profileFetch, timeout])
            if (data) userProfile.value = data
        } else if (!session?.user) {
            userProfile.value = null
        }
        // TOKEN_REFRESHED: no se re-fetchea el perfil, userSession ya se actualizó arriba
    })

    async function login(email: string, pass: string, keepSession: boolean = false) {
        const { data, error } = await supabase.auth.signInWithPassword({ email, password: pass })
        if (error) throw new Error(error.message)

        if (data.user) {
            // Manejo de persistencia: Si el usuario NO quiere mantener sesión iniciada,
            // movemos el token de localStorage a sessionStorage.
            if (!keepSession) {
                const storageKey = `sb-bjgixlugjzsccazdfmph-auth-token`
                const sessionData = localStorage.getItem(storageKey)
                if (sessionData) {
                    sessionStorage.setItem(storageKey, sessionData)
                    localStorage.removeItem(storageKey)
                }
            }

            userSession.value = data.session
            userProfile.value = {
                id: data.user.id,
                email: data.user.email,
                full_name: data.user.user_metadata?.full_name || data.user.email,
                role: data.user.user_metadata?.role || 'PASSENGER'
            }
        }
    }

    async function register(email: string, pass: string, fullName: string, autoLocation: boolean = false) {
        console.log('Realizando signUp en Supabase...')
        const { data, error } = await supabase.auth.signUp({
            email,
            password: pass,
            options: {
                data: {
                    full_name: fullName,
                    role: 'PASSENGER',
                    auto_location: autoLocation
                }
            }
        })

        if (error) throw new Error(error.message)

        // Supabase retorna sesión inmediata si auto-confirm está activado.
        if (data.session && data.user) {
            userSession.value = data.session
            userProfile.value = {
                id: data.user.id,
                email: data.user.email,
                full_name: data.user.user_metadata?.full_name || data.user.email,
                role: data.user.user_metadata?.role || 'PASSENGER'
            }
        }
    }

    function logout() {
        // Limpiar estado de Pinia inmediatamente
        userSession.value = null
        userProfile.value = null

        // Limpiar TODA la sesión del navegador sin esperar a Supabase
        localStorage.clear()
        sessionStorage.clear()

        // Limpiar IndexedDB donde Supabase guarda tokens
        try {
            indexedDB.deleteDatabase('supabase-js-auth')
            indexedDB.deleteDatabase('supabase')
        } catch (_) { }

        // Llamar signOut en background (sin await - no bloqueamos)
        supabase.auth.signOut().catch(() => { })

        // Redirigir forzando recarga completa del navegador
        window.location.replace('/login')
    }

    async function updateProfile(updates: any) {
        if (!userSession.value?.user?.id) return

        const { error } = await supabase
            .from('users')
            .update(updates)
            .eq('id', userSession.value.user.id)

        if (!error) {
            userProfile.value = { ...userProfile.value, ...updates }
        } else {
            console.error('SIB | Error al actualizar perfil:', error)
        }
    }

    return {
        userSession,
        userProfile,
        role,
        userName,
        isAuthenticated,
        isAdmin,
        isDriver,
        isPromoter,
        isPassenger,
        login,
        register,
        logout,
        updateProfile
    }
})
