import { root } from '@repo/core'
import { type ListAnnouncementsInput, type ListAnnouncementsResult, AnnouncementController, type Announcement } from '@repo/sdk'
import { useCallback, useRef, useState } from 'react'

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

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

type ListAnnouncementsParams = ListAnnouncementsInput

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

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

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

        const announcement = root.get(AnnouncementController)
        const requestParams: ListAnnouncementsInput = {
            ...DEFAULT_PARAMS,
            ...initialParams,
            ...params,
            page: params?.page ?? initialParams?.page ?? 1,
        }

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

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

        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 announcement = root.get(AnnouncementController)
        const requestParams: ListAnnouncementsInput = {
            ...DEFAULT_PARAMS,
            ...initialParams,
            page: nextPage,
        }

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

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

        const newAnnouncements = newData?.announcements || []
        const totalPages = newData?.totalPages || 1
        hasMoreRef.current = nextPage < totalPages
        currentPageRef.current = nextPage

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

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

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

export type { Announcement }
