import { root } from '@repo/core'
import { CategoryController, type ListCategoriesInput, type ListCategoriesResult } from '@repo/sdk'
import { useState, useEffect } from 'react'
import { create } from 'zustand'

import { type ApiError } from '@/lib/types'

import { OWNER_ID } from '@/lib/auth'
import { handleError } from './use-error'

interface CategoriesState {
    data: ListCategoriesResult | null | undefined
    loading: boolean
    error: ApiError | null
    hasLoaded: boolean
}

export const useCategoriesStore = create<CategoriesState>((set) => ({
    data: undefined,
    loading: false,
    error: null,
    hasLoaded: false,
}))

export const useCategories = (params?: ListCategoriesInput) => {
    const store = useCategoriesStore()
    const [localLoading, setLocalLoading] = useState(false)

    useEffect(() => {
        if (!store.hasLoaded && !store.loading && !localLoading) {
            load()
        }
    }, [])

    const load = async (inputParams?: ListCategoriesInput) => {
        if (store.loading || localLoading) return

        try {
            setLocalLoading(true)
            useCategoriesStore.setState({ loading: true })
            const category = root.get(CategoryController)

            // Merge params: inputParams > params > defaults
            const mergedParams = {
                page: 1,
                limit: 1000,
                isActive: true,
                orderBy: 'sortOrder' as const,
                order: 'desc' as const,
                withChildren: true,
                ownerId: OWNER_ID,
                ...(params ?? {}),
                ...(inputParams ?? {}),
            }

            const { data, error } = await handleError(async () => await category.list(mergedParams))

            if (error) {
                useCategoriesStore.setState({ data: null, error, loading: false, hasLoaded: true })
                return
            }
            useCategoriesStore.setState({ data, loading: false, error: null, hasLoaded: true })
        } catch (e) {
            useCategoriesStore.setState({ error: e as ApiError, loading: false, hasLoaded: true })
        } finally {
            setLocalLoading(false)
        }
    }

    return {
        load,
        loading: store.loading || localLoading,
        error: store.error,
        data: store.data,
    }
}

