import { TAB_NAMES } from 'components/label-purchase/packages';
import { useThrottledStateChange } from '../utils';
import { LabelPurchaseContextType } from 'context/label-purchase';
import { CustomPackage } from 'types';
import { useCallback } from '@wordpress/element';

export const useRatesEffects = ( {
	rates: { updateRates, fetchRates },
	customs: { isCustomsNeeded },
	shipment: { getCurrentShipmentDate },
	weight: { getShipmentTotalWeight },
	packages: { getCustomPackage, getSelectedPackage, currentPackageTab },
	nextDesign,
}: LabelPurchaseContextType ) => {
	// Update rates when isCustomsNeeded changes
	useThrottledStateChange( isCustomsNeeded(), updateRates );

	// Update rates when the shipment dates changes
	useThrottledStateChange( getCurrentShipmentDate(), updateRates );

	// Update rates when the custom package dimensions change
	const hasValidDimensions = ( pkg: CustomPackage ) => {
		const { length, width, height } = pkg;
		return (
			parseInt( length ?? '0', 10 ) > 0 &&
			parseInt( width ?? '0', 10 ) > 0 &&
			parseInt( height ?? '0', 10 ) > 0
		);
	};

	const hasValidWeight = ( weight: number ) => weight > 0;

	const customPackage = getCustomPackage();
	const selectedPackage = getSelectedPackage();
	const totalWeight = getShipmentTotalWeight();

	// Memoize the custom package state to avoid unnecessary re-renders
	const customPackageState = useCallback( () => {
		if (
			nextDesign &&
			customPackage &&
			currentPackageTab === TAB_NAMES.CUSTOM_PACKAGE &&
			hasValidWeight( totalWeight ) &&
			hasValidDimensions( customPackage )
		) {
			return `${ customPackage.type }-${ customPackage?.width }x${ customPackage?.height }x${ customPackage?.length }-${ totalWeight }`;
		}
		return null;
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [
		nextDesign,
		customPackage?.type,
		customPackage?.width,
		customPackage?.height,
		customPackage?.length,
		totalWeight,
		currentPackageTab,
	] );

	// Update rates when the custom package dimensions change
	useThrottledStateChange( customPackageState(), () =>
		fetchRates( customPackage )
	);

	// Memoize the selected package state to avoid unnecessary re-renders
	const selectedPackageState = useCallback( () => {
		if (
			nextDesign &&
			selectedPackage &&
			hasValidWeight( totalWeight ) &&
			currentPackageTab === TAB_NAMES.CARRIER_PACKAGE
		) {
			return selectedPackage.id + '-' + totalWeight;
		}
		return null;
	}, [ nextDesign, selectedPackage?.id, totalWeight, currentPackageTab ] ); // eslint-disable-line react-hooks/exhaustive-deps

	// Update rates when the selected package changes
	useThrottledStateChange( selectedPackageState(), updateRates );
};
