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

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

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

type GetUserLikesParams = Partial<Omit<GetUserLikesInput, 'page'>>

const DEFAULT_PARAMS = {
    limit: 20,
}

export const useUserLikes = (initialParams?: GetUserLikesParams) => {
    const [loading, setLoading] = useState(false)
    const [loadingMore, setLoadingMore] = useState(false)
    const [error, setError] = useState<ApiError | null>(null)
    const [data, setData] = useState<GetUserLikesResponse>()
    const currentPageRef = useRef(1)
    const hasMoreRef = useRef(true)

    const execute = useCallback(async (params?: GetUserLikesParams) => {
        setLoading(true)
        setError(null)
        currentPageRef.current = params?.page || initialParams?.page || 1

        const controller = root.get(TemplateSocialController)
        const requestParams: GetUserLikesInput = {
            ...DEFAULT_PARAMS,
            ...initialParams,
            ...params,
            page: params?.page ?? initialParams?.page ?? 1,
        }

        const { data, error } = await handleError(
            async () => await controller.getUserLikes(requestParams),
        )

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

        const likes = data?.likes || []
        const currentPage = requestParams.page || 1
        const total = data?.total || 0
        const limit = requestParams.limit || 20
        const totalPages = Math.ceil(total / limit)
        hasMoreRef.current = currentPage < totalPages
        setData(data)
        setLoading(false)
        return { data, error: null }
    }, [initialParams])

    const loadMore = useCallback(async () => {
        if (loadingMore || loading || !hasMoreRef.current) return { data: undefined, error: null }

        setLoadingMore(true)
        const nextPage = currentPageRef.current + 1

        const controller = root.get(TemplateSocialController)
        const requestParams: GetUserLikesInput = {
            ...DEFAULT_PARAMS,
            ...initialParams,
            page: nextPage,
        }

        const { data: newData, error } = await handleError(
            async () => await controller.getUserLikes(requestParams),
        )

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

        const newLikes = newData?.likes || []
        const total = newData?.total || 0
        const limit = requestParams.limit || 20
        const totalPages = Math.ceil(total / limit)
        hasMoreRef.current = nextPage < totalPages
        currentPageRef.current = nextPage

        setData((prev) => ({
            ...newData,
            likes: [...(prev?.likes || []), ...newLikes],
        }))
        setLoadingMore(false)
        return { data: newData, error: null }
    }, [loading, loadingMore, initialParams])

    const refetch = useCallback(() => {
        hasMoreRef.current = true
        return execute()
    }, [execute])

    return {
        data,
        likes: data?.likes || [],
        loading,
        loadingMore,
        error,
        execute,
        refetch,
        loadMore,
        hasMore: hasMoreRef.current,
    }
}
