import {
    useEffect,
    useState,
} from 'react';

import { rpc } from '@/api/request';
import { SortDFInput } from '@/api/types';

type HashUpdateProps = {
    lock: boolean;
    collection?: string;
    limit?: number;
    offset?: number;
    search?: string | null;
    sort?: SortDFInput;
    stage?: string;
    currentHash?: string | null;
    filter: any;
    pipeline: any;
    onHashUpdate: () => void;
}

const HashUpdate = ({
    filter,
    lock, collection, limit, offset, search, sort, currentHash, onHashUpdate, pipeline }: HashUpdateProps) => {


    const [hashLoading, setHashLoading] = useState<boolean>(false);

    useEffect(() => {



        if (lock) return;

        if (!collection) return;

        setHashLoading(false);


        const intervalHashUpdate = setInterval(() => {



            setHashLoading(true);
            rpc.data({


                collection: collection,
                limit: limit,
                offset: offset,
                search: (!!search && !!search.trim()) ? search.trim() : undefined,
                sort: !!sort ? sort : undefined,
                filter: !!filter ? filter : undefined,
                pipeline: !!pipeline ? pipeline : undefined,
                onlyHash: true,
            }).then((newHash) => {
                console.log('HASH UPDATE ➡️ newHash', newHash.result?.hash);
                console.log('HASH UPDATE ➡️currentHash', currentHash);
                if (!!newHash?.result?.hash && newHash.result.hash !== currentHash) {




                    onHashUpdate();
                }
            }).catch((err) => {

            }).finally(() => {
                setHashLoading(false);
            });

        }, 5000);


        return () => {
            clearInterval(intervalHashUpdate);
        }


    }, [lock, collection, limit, offset, search, sort, filter, currentHash, onHashUpdate]);




    // return <Badge>{hashLoading ? 'Updating...' : 'Updated'}</Badge>
    return <></>

}

export default HashUpdate;