import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { twMerge } from "tailwind-merge";

import { SwitchChevron } from "@components/common/Icons";
import {
	addOutputToken,
	removeOutputToken,
	resetOutputTokenRatios,
	setFromChainId,
	setFromTokens,
	setToChainId,
} from "@store/quoteParamSlice";
import type { ReduxStateType } from "@store/types";

export const TokensSwitch = ({ classNames }: { classNames?: string }) => {
	const dispatch = useDispatch();

	const fromTokens = useSelector(
		(state: ReduxStateType) => state.quoteParams.fromTokens,
	);
	const toTokens = useSelector(
		(state: ReduxStateType) => state.quoteParams.toTokens,
	);

	const disabled = !fromTokens?.length || !toTokens?.length;

	// biome-ignore format:
	const style = twMerge(
		`bn-size-9 bn-rounded-full bn-border-none bn-bg-layer-3 bn-flex bn-items-center bn-justify-center hover:bn-rotate-180 bn-p-0 ${disabled ? 'bn-opacity-50': ''}`,
		classNames,
	);

	function switchTokens() {
		const _newFromToken = toTokens?.[0];
		const _newToToken = fromTokens?.[0];

		if (_newFromToken && _newToToken) {
			dispatch(setFromTokens(_newFromToken));
			dispatch(setFromChainId(_newFromToken.chainId));

			dispatch(addOutputToken({ id: 0, token: _newToToken }));
			dispatch(setToChainId(_newToToken.chainId));

			// removing 2nd token if added as we do not support multi-input yet
			if (toTokens?.length > 1) {
				dispatch(removeOutputToken({ id: 1 }));
				dispatch(resetOutputTokenRatios());
			}
		}
	}

	return (
		<button
			className={style}
			type="button"
			disabled={disabled}
			onClick={switchTokens}
		>
			<SwitchChevron />
		</button>
	);
};
