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

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

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


type ListTemplatesParams = Omit<ListTemplatesInput, 'ownerId'>

const DEFAULT_PARAMS = {
    limit: 20,
    sortBy: 'createdAt' as const,
    sortOrder: 'desc' as const,
}

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

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

        const template = root.get(TemplateController)
        const requestParams: ListTemplatesInput = {
            ...DEFAULT_PARAMS,
            ...initialParams,
            ...params,
            page: params?.page ?? initialParams?.page ?? 1,
            ownerId: OWNER_ID,
        }

        const { data, error } = await handleError(
            async () => await template.list(requestParams),
        )

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

        const templates = data?.templates || []
        const currentPage = requestParams.page || 1
        const totalPages = data?.totalPages || 1
        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 template = root.get(TemplateController)
        const requestParams: ListTemplatesInput = {
            ...DEFAULT_PARAMS,
            ...initialParams,
            page: nextPage,
            ownerId: OWNER_ID,
        }

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

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

        const newTemplates = newData?.templates || []
        const totalPages = newData?.totalPages || 1
        hasMoreRef.current = nextPage < totalPages
        currentPageRef.current = nextPage

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

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

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

export type { TemplateDetail }

