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

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

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);


    const hashUpdate = useCallback(() => {

        if (!collection) return;

        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);
        });
    }, [collection, limit, offset, search, sort, filter, pipeline, currentHash, onHashUpdate]);

    useEffect(() => {



        if (lock) return;

        if (!collection) return;


        const unsubscribe = EventEmitter.subscribe("updateCollectionData", hashUpdate);


        setHashLoading(false);


        const intervalHashUpdate = setInterval(() => {


            hashUpdate();
        }, 5000);


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


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




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

}

export default HashUpdate;