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

export interface Favorite {
    id: string
    user_id: string
    item_type: 'coupon' | 'business' | 'taxi' | 'route'
    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)

    // Computed
    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'))

    // Actions
    async function loadFavorites() {
        isLoading.value = true
        try {
            const response = await apiClient.get('/api/favorites')
            favorites.value = response.data
        } catch (error) {
            console.error('Error loading favorites:', error)
        } finally {
            isLoading.value = false
        }
    }

    async function addFavorite(
        itemType: 'coupon' | 'business' | 'taxi' | 'route',
        itemId: string,
        itemName?: string,
        itemImage?: string
    ) {
        try {
            const response = await apiClient.post('/api/favorites', {
                item_type: itemType,
                item_id: itemId,
                item_name: itemName,
                item_image: itemImage
            })
            favorites.value.unshift(response.data)
            return true
        } catch (error: any) {
            if (error.response?.status === 400) {
                // Already favorited
                return false
            }
            console.error('Error adding favorite:', error)
            throw error
        }
    }

    async function removeFavorite(itemType: string, itemId: string) {
        try {
            await apiClient.delete(`/api/favorites/${itemType}/${itemId}`)
            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',
        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,
        loadFavorites,
        addFavorite,
        removeFavorite,
        toggleFavorite,
        isFavorite
    }
})
