import React, { Fragment, ReactNode, useEffect, useState } from 'react';
import CircularProgress from '@mui/material/CircularProgress';
import Box from '@mui/material/Box';
import dynamic from 'next/dynamic';

const Animations = dynamic(() => import('@/components/animations'));

interface APIFetchProps {
    children: ReactNode;
    isLoading?: boolean | number | null;
    lengthCheckObject?: any;
    messageContent?: any;
    notLengthCheckObject?: boolean;
    animatedLoading?: string;
    customAnimation?: ReactNode;
    blocks?: number;
}

export const APIFetch: React.FC<APIFetchProps> = ({ children, isLoading = false, animatedLoading = '', customAnimation, lengthCheckObject = {}, notLengthCheckObject = false, messageContent = '', blocks }) => {

    const [isClient, setIsClient] = useState(false);

    useEffect(() => {
        setIsClient(true)
    }, []);


    if ((isClient) && (!isLoading)) {
        if (validateData(lengthCheckObject || '') || notLengthCheckObject) {
            return children ?? <></>
        } else {
            return (
                <>
                    {messageContent !== '' && <div className='flex justify-center mb-4 text-red-500'>{messageContent}</div>}
                </>
            )
        }
    } else {
        return (
            <Fragment>
                {customAnimation ? customAnimation : animatedLoading !== '' &&
                    <Animations
                        animation={animatedLoading}
                        blocks={blocks}
                    />
                    ||
                    <div className='flex justify-center my-14 md:my-28'>
                        <Box >
                            <CircularProgress />
                        </Box>
                    </div>
                }
            </Fragment>

        )
    }
};

export const validateData = (objectApi: any) => {
    if (!objectApi) return false;

    if (Array.isArray(objectApi)) {
        return objectApi.length > 0;
    }

    if (typeof objectApi === 'object') {
        return Object.keys(objectApi).length > 0;
    }

    return !!objectApi;
};