import { root } from '@repo/core'
import { TemplateController, type TemplateDetail } from '@repo/sdk'
import { useCallback, useState } from 'react'

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

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

interface UseTemplateDetailParams {
    id: string
}

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

    const execute = useCallback(async (params: UseTemplateDetailParams) => {
        setLoading(true)
        setError(null)

        const template = root.get(TemplateController)
        const { data, error } = await handleError(async () => await template.get(params.id))

        if (error) {
            setError(error)
            setLoading(false)
            return { data: undefined, error }
        }

        setData(data)
        setLoading(false)
        return { data, error: null }
    }, [])

    const refetch = useCallback(
        (params: UseTemplateDetailParams) => {
            return execute(params)
        },
        [execute],
    )

    return {
        data,
        loading,
        error,
        execute,
        refetch,
    }
}

export type { TemplateDetail }
