import { root } from '@repo/core'
import { ActivityController, type ListActivitiesInput, type ListActivitiesResult } from '@repo/sdk'
import { useState } from 'react'

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

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


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

    const load = async (params?: ListActivitiesInput) => {
        try {
            setLoading(true)
            const activity = root.get(ActivityController)
            const { data, error } = await handleError(
                async () =>
                    await activity.list({
                        page: 1,
                        limit: 10,
                        isActive: true,
                        orderBy: 'sortOrder',
                        order: 'desc',
                        ownerId: OWNER_ID,
                        ...params,
                    }),
            )
            if (error) {
                setError(error)
                return
            }
            setData(data)
        } catch (e) {
            setError(e as ApiError)
        } finally {
            setLoading(false)
        }
    }

    return {
        load,
        loading,
        error,
        data,
    }
}
