'use client'

import Loader from "@/Components/Loaders/Loader"
import { makeClassName } from "@/utils"
import React, { ReactElement, ReactNode } from "react"

const ViewWithLoader = ({
    data,
    isLoading,
    isFetching,
    error,
    children,
    defaultLoaderClassName = 'mx-auto mt-10 absolute top-0 left-0 right-0',
    loaderClassName,
    keepExistingContentWhileLoading = true,
    ErrorComponent,
    LoaderComponent

}: {
    data: any,
    isLoading: boolean,
    isFetching?: boolean,
    error: Error | null,
    children: ReactNode,
    defaultLoaderClassName?: string,
    loaderClassName?: string,
    keepExistingContentWhileLoading?: boolean,
    ErrorComponent?: (props: { error: Error }) => ReactElement
    LoaderComponent?: React.FC<{ className?: string }>
}): ReactElement => {

    const showError = error !== null && error !== undefined
    const showLoader = isLoading || data === undefined || isFetching === true
    const showChildren = keepExistingContentWhileLoading || (!isLoading && data !== undefined && (error === null || error === undefined))

    return (
        <>
            {showError && (ErrorComponent ? <ErrorComponent error={error as Error} /> : <div className="text-red-500 text-center mt-10">Error: {(error as Error).message}</div>)}
            {showLoader &&
                (
                    LoaderComponent !== undefined
                        ? <LoaderComponent className={makeClassName({
                            defaultClassName: defaultLoaderClassName,
                            className: loaderClassName
                        })} />
                        :
                        <div className='absolute top-0 bottom-0 left-0 right-0 bg-white/60 z-30'>
                            <Loader className={makeClassName({
                                defaultClassName: defaultLoaderClassName,
                                className: loaderClassName
                            })} />
                        </div >
                )
            }
            {showChildren && children}

        </>
    )
}

export default ViewWithLoader