import { root } from '@repo/core'
import { MessageController, type Message, type ListMessagesResult } from '@repo/sdk'
import { useCallback, useRef, useState } from 'react'

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

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

interface ListMessagesParams {
    page?: number
    limit?: number
    type?: 'SYSTEM' | 'ACTIVITY' | 'BILLING' | 'MARKETING'
    isRead?: boolean
}

const DEFAULT_PARAMS = {
    limit: 20,
    orderBy: 'createdAt',
    order: 'desc',
}

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

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

        const messageController = root.get(MessageController)
        const requestParams = {
            ...DEFAULT_PARAMS,
            ...initialParams,
            ...params,
            page: params?.page ?? initialParams?.page ?? 1,
        }

        const { data, error } = await handleError(
            async () => await messageController.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 messageController = root.get(MessageController)
        const requestParams = {
            ...DEFAULT_PARAMS,
            ...initialParams,
            page: nextPage,
        }

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

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

        const newMessages = newData?.messages || []
        const totalPages = newData?.totalPages || 1
        hasMoreRef.current = nextPage < totalPages
        currentPageRef.current = nextPage

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

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

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

export type { Message }
