import { useSelector } from "react-redux";
import type { Address } from "viem";

import { canViewFeature } from "@components/FeatureFlag/config";
import type { ReduxStateType } from "@store/types";

export const useManualHistory = ({
	userAddress,
	pageNumber,
	pageSize,
}: { userAddress: Address; pageNumber: number; pageSize: number }) => {
	const isFeatureEnabled = canViewFeature("MANUAL_MODE");
	const manualHistory = useSelector(
		(state: ReduxStateType) => state.global.manualHistory,
	);

	// Check if feature is enabled and userAddress is provided
	if (!isFeatureEnabled || !userAddress) {
		return { data: null };
	}

	// Paginate the manual history data
	const userHistory = manualHistory?.[userAddress.toLowerCase()] || [];
	const paginatedData = [...userHistory]
		?.reverse()
		.slice((pageNumber - 1) * pageSize, pageNumber * pageSize);

	const totalPages = Math.ceil(userHistory.length / pageSize);

	return {
		paginatedData: paginatedData,
		allData: userHistory,
		totalPages,
		dataAvailable: Boolean(userHistory?.length),
	};
};
