import { root } from '@repo/core'
import { TemplateSocialController } from '@repo/sdk'
import { useCallback, useState } from 'react'

import { type ApiError } from '@/lib/types'
import { handleError } from './use-error'

export const useTemplateLike = (templateId?: string) => {
    const [liked, setLiked] = useState<boolean>(false)
    const [loading, setLoading] = useState<boolean>(false)
    const [error, setError] = useState<ApiError | null>(null)

    const like = useCallback(async (): Promise<{ error?: ApiError }> => {
        if (!templateId) {
            return { error: { message: 'TemplateId is required' } as ApiError }
        }

        setLoading(true)
        setError(null)

        const social = root.get(TemplateSocialController)
        const { data, error } = await handleError(
            async () => await social.like({ templateId })
        )

        setLoading(false)

        if (error) {
            setError(error)
            return { error }
        }

        setLiked(true)
        return {}
    }, [templateId])

    const unlike = useCallback(async (): Promise<{ error?: ApiError }> => {
        if (!templateId) {
            return { error: { message: 'TemplateId is required' } as ApiError }
        }

        setLoading(true)
        setError(null)

        const social = root.get(TemplateSocialController)
        const { data, error } = await handleError(
            async () => await social.unlike({ templateId })
        )

        setLoading(false)

        if (error) {
            setError(error)
            return { error }
        }

        setLiked(false)
        return {}
    }, [templateId])

    const checkLiked = useCallback(async (): Promise<{ error?: ApiError }> => {
        if (!templateId) {
            return { error: { message: 'TemplateId is required' } as ApiError }
        }

        setLoading(true)
        setError(null)

        const social = root.get(TemplateSocialController)
        const { data, error } = await handleError(
            async () => await social.checkLiked({ templateId })
        )

        setLoading(false)

        if (error) {
            setError(error)
            return { error }
        }

        setLiked(data?.liked || false)
        return {}
    }, [templateId])

    return {
        liked,
        loading,
        error,
        like,
        unlike,
        checkLiked,
    }
}
