import { useEffect, useRef } from "react";
import { useDispatch } from "react-redux";
import type { Address } from "viem";
import { useAccount } from "wagmi";

import { useManualHistory } from "@hooks/apis/manual/useManualHistory";
import { resetManualHistory } from "@store/globalSlice";

export const useHistoryCleanup = () => {
	const { address } = useAccount();
	const dispatch = useDispatch();
	const { allData: data } = useManualHistory({
		userAddress: address as Address,
		pageNumber: 1,
		pageSize: 5,
	});

	const firstRender = useRef(true);

	useEffect(() => {
		if (!data?.length || !firstRender.current || !address) return;
		// const oneWeekAgo = Math.floor(Date.now() / 1000) - 7 * 24 * 60 * 60; // Convert to seconds

		const filtered = [...data].reverse().slice(0, 10); // reversing the data as the latest items are pushed to the array
		dispatch(resetManualHistory({ address, data: filtered.reverse() })); // reversing again before updating store
		firstRender.current = false;
	}, [data, dispatch, address]);
};
