import { computed } from 'vue'

// Use a more flexible Item interface that works with both ItemsList and ListsPage
interface BaseItem {
    id: number | string
    tempId?: string
    name: string
    is_complete: boolean
    category_id?: number | null
    price?: number | null
    claimed_by_user_id?: number | null
    quantity?: string | null
    version?: number
    updated_at?: string
    updating?: boolean
}

export interface Category {
    id: number
    name: string
}

export interface ItemGroup {
    categoryName: string
    items: BaseItem[]
}

export function useItemHelpers() {

    const groupItemsByCategory = (items: BaseItem[], categories: Category[], uncategorizedLabel = 'Uncategorized') => {
        const groups: Record<string, ItemGroup> = {}

        items.forEach(item => {
            const categoryId = item.category_id
            const category = categories.find(c => c.id === categoryId)
            const categoryName = category ? category.name : uncategorizedLabel

            if (!groups[categoryName]) {
                groups[categoryName] = { categoryName, items: [] }
            }
            groups[categoryName].items.push(item)
        })

        return Object.values(groups)
    }

    const getCompletedCount = (items: BaseItem[]) => {
        return items.filter(item => item.is_complete).length
    }

    const getCompletionPercentage = (items: BaseItem[]) => {
        if (items.length === 0) return 0
        return Math.round((getCompletedCount(items) / items.length) * 100)
    }

    const getPreviewItems = (items: BaseItem[], limit = 3) => {
        return items.slice(0, limit)
    }

    const getIncompleteTasks = (items: BaseItem[]) => {
        return items.filter(item => !item.is_complete)
    }

    const getCompletedTasks = (items: BaseItem[]) => {
        return items.filter(item => item.is_complete)
    }

    const getTotalEstimatedCost = (items: BaseItem[]) => {
        return items.reduce((total, item) => {
            return total + (item.price ? parseFloat(String(item.price)) : 0)
        }, 0)
    }

    const getClaimedItems = (items: BaseItem[]) => {
        return items.filter(item => item.claimed_by_user_id)
    }

    const buildCategoryOptions = (categories: Category[], includeNone = true) => {
        const options: { label: string; value: number | null }[] = categories.map(cat => ({
            label: cat.name,
            value: cat.id
        }))

        if (includeNone) {
            options.unshift({ label: 'No Category', value: null })
        }

        return options
    }

    return {
        groupItemsByCategory,
        getCompletedCount,
        getCompletionPercentage,
        getPreviewItems,
        getIncompleteTasks,
        getCompletedTasks,
        getTotalEstimatedCost,
        getClaimedItems,
        buildCategoryOptions
    }
} 