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

export interface Favorite {
    id: string
    user_id: string
    item_type: 'coupon' | 'business' | 'taxi' | 'route' | 'stop' | 'shuttle'
    item_id: string
    item_name?: string
    item_image?: string
    created_at: string
}

export const useFavoritesStore = defineStore('favorites', () => {
    const favorites = ref<Favorite[]>([])
    const isLoading = ref(false)

    const coupons = computed(() => favorites.value.filter(f => f.item_type === 'coupon'))
    const businesses = computed(() => favorites.value.filter(f => f.item_type === 'business'))
    const taxis = computed(() => favorites.value.filter(f => f.item_type === 'taxi'))
    const routes = computed(() => favorites.value.filter(f => f.item_type === 'route'))
    const stops = computed(() => favorites.value.filter(f => f.item_type === 'stop'))
    const shuttles = computed(() => favorites.value.filter(f => f.item_type === 'shuttle'))

    async function loadFavorites() {
        isLoading.value = true
        // Safety: si la red está inestable al awakening del background, no quedar cargando
        const safetyTimer = setTimeout(() => {
            if (isLoading.value) {
                console.warn('SIB | favoritesStore: safety timeout — reseteando isLoading')
                isLoading.value = false
            }
        }, 12000)
        try {
            const { data: userData } = await supabase.auth.getUser()
            if (!userData?.user) { favorites.value = []; return }

            const { data, error } = await supabase
                .from('favorites')
                .select('*')
                .eq('user_id', userData.user.id)
            if (error) throw error
            favorites.value = data as Favorite[]
        } catch (error) {
            console.error('Error loading favorites:', error)
        } finally {
            clearTimeout(safetyTimer)
            isLoading.value = false
        }
    }

    async function addFavorite(
        itemType: 'coupon' | 'business' | 'taxi' | 'route' | 'stop' | 'shuttle',
        itemId: string,
        itemName?: string,
        itemImage?: string
    ) {
        try {
            const { data: userData } = await supabase.auth.getUser()
            if (!userData?.user) throw new Error('Not authenticated')

            const { data, error } = await supabase.from('favorites').insert([{
                user_id: userData.user.id,
                item_type: itemType,
                item_id: itemId,
                item_name: itemName,
                item_image: itemImage
            }]).select().single()
            if (error) throw error
            favorites.value.unshift(data as Favorite)
            return true
        } catch (error) {
            console.error('Error adding favorite:', error)
            throw error
        }
    }

    async function removeFavorite(itemType: string, itemId: string) {
        try {
            const { data: userData } = await supabase.auth.getUser()
            if (!userData?.user) throw new Error('Not authenticated')

            const { error } = await supabase.from('favorites')
                .delete()
                .eq('user_id', userData.user.id)
                .eq('item_type', itemType)
                .eq('item_id', itemId)
            if (error) throw error
            favorites.value = favorites.value.filter(
                f => !(f.item_type === itemType && f.item_id === itemId)
            )
            return true
        } catch (error) {
            console.error('Error removing favorite:', error)
            throw error
        }
    }

    async function toggleFavorite(
        itemType: 'coupon' | 'business' | 'taxi' | 'route' | 'stop' | 'shuttle',
        itemId: string,
        itemName?: string,
        itemImage?: string
    ) {
        const existing = favorites.value.find(
            f => f.item_type === itemType && f.item_id === itemId
        )
        if (existing) {
            await removeFavorite(itemType, itemId)
            return false
        } else {
            await addFavorite(itemType, itemId, itemName, itemImage)
            return true
        }
    }

    function isFavorite(itemType: string, itemId: string): boolean {
        return favorites.value.some(
            f => f.item_type === itemType && f.item_id === itemId
        )
    }

    return {
        favorites, isLoading, coupons, businesses, taxis, routes, stops, shuttles,
        loadFavorites, addFavorite, removeFavorite, toggleFavorite, isFavorite
    }
})
