import { useSelector } from "react-redux";

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

export const useManualHistory = ({
	userAddresses,
	pageNumber,
	pageSize,
}: {
	userAddresses: string[] | undefined;
	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 || !userAddresses || !userAddresses.length) {
		return { data: null };
	}

	const addressDataMap = userAddresses.reduce(
		(acc, userAddress) => {
			acc[userAddress.toLowerCase()] =
				manualHistory?.[userAddress.toLowerCase()] || [];
			return acc;
		},
		{} as Record<string, ManualOrderData[]>,
	);

	const manualHistoryData: ManualOrderData[][] = [];

	for (const userAddress of userAddresses) {
		manualHistoryData.push(manualHistory?.[userAddress.toLowerCase()] || []);
	}

	const flattenedManualHistoryData = manualHistoryData
		.flat()
		.sort((a, b) => a.orderTimestamp - b.orderTimestamp);

	// Paginate the manual history data
	const userHistory = flattenedManualHistoryData;
	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),
		addressDataMap,
	};
};
