import { useCallback, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";

import { RoundedCheckbox } from "@components/common/RoundedCheckbox";
import { useActiveRoute } from "@hooks/apis/common/quote/useActiveRoute";
import { toggleAddOnRefuel } from "@store/quoteParamSlice";
import type { ReduxStateType } from "@store/types";
import { NATIVE_TOKEN_ADDRESS } from "@utils/constants";
import { isWrapUnwrapCase } from "@utils/isWrapUnwrapCase";
import { onToggleRefuel } from "../../../analytics/events";
import { AddOnItem } from "./AddOnItem";

/**
 * RefuelCheckbox component that allows users to enable/disable the refuel add-on
 * This component automatically disables the refuel option for swap routes and wrap/unwrap cases
 */
export const RefuelCheckbox = () => {
	const dispatch = useDispatch();
	const { data: activeRoute } = useActiveRoute();
	const { addOnRefuel, fromChainId, toChainId, toTokens } = useSelector(
		(state: ReduxStateType) => state.quoteParams,
	);

	const dispatchValue = useCallback(
		(value: boolean) => {
			dispatch(toggleAddOnRefuel(value));
		},
		[dispatch],
	);

	const { isSwapRoute } = activeRoute || {};
	// not used anywhere. refuel works for manual even if the destination token is native.
	const isDestinationNative =
		toTokens?.[0]?.address?.toLowerCase() === NATIVE_TOKEN_ADDRESS.toLowerCase();

	const disableRefuel =
		fromChainId === toChainId ||
		isSwapRoute ||
		isWrapUnwrapCase(activeRoute) ||
		isDestinationNative;

	useEffect(() => {
		if (disableRefuel) {
			dispatchValue(false);
		}
	}, [disableRefuel, dispatchValue]);

	return (
		<AddOnItem
			label="Enable Refuel"
			iconName="local_gas_station"
			actionItem={
				<RoundedCheckbox
					isChecked={Boolean(addOnRefuel)}
					setIsChecked={(value) => {
						dispatchValue(value);
						onToggleRefuel({ enabled: value });
					}}
					id="bungee-refuel"
					disabled={Boolean(disableRefuel)}
				/>
			}
			active={Boolean(addOnRefuel)}
			disabled={Boolean(disableRefuel)}
			disabledMsg="Refuel is disabled"
		/>
	);
};
