import { root } from '@repo/core'
import { type ListTagsInput, type ListTagsResult, TagController } from '@repo/sdk'
import { useState } from 'react'

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

import { handleError } from './use-error'

export const useTags = () => {
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState<ApiError | null>(null)
    const [data, setData] = useState<ListTagsResult>()

    const load = async (params?: ListTagsInput) => {
        try {
            setLoading(true)
            const tag = root.get(TagController)
            const { data, error } = await handleError(
                async () =>
                    await tag.list({
                        page: params?.page || 1,
                        limit: params?.limit || 20,
                        orderBy: 'sortOrder',
                        order: 'desc',
                        ownerId: process.env.EXPO_PUBLIC_OWNER_ID || '',
                    }),
            )

            if (error) {
                setError(error)
                return
            }

            setData(data)
        } catch (e) {
            setError(e as ApiError)
        } finally {
            setLoading(false)
        }
    }

    return { load, loading, error, data }
}
