import { motion } from "framer-motion";
import React, { useState } from "react";
import { useSelector } from "react-redux";

import type { Token } from "@providers/ConfigProvider";
import type { ReduxStateType } from "@store/types";
import { adjustDecimals } from "@utils/adjustDecimals";
import { isWrapUnwrapCase } from "@utils/isWrapUnwrapCase";
import { useFetchQuote } from "../hooks/apis/useFetchQuote";
import { useTheme } from "../hooks/useTheme";
import { getBorderRadius } from "../utils/getBorderRadius";
import { ReviewSection } from "./Review/ReviewSection";
import { MIcon } from "./common/MIcon";
import { RefreshButton } from "./common/RefreshButton";
import { Tooltip } from "./common/Tooltip";
import { TransferType } from "./common/TransferType";

export const ReviewDropdown = () => {
	const theme = useTheme();
	const [openDropdown, setOpenDropdown] = useState<boolean>(false);
	const { data: quoteData, refetch } = useFetchQuote();

	const [showSrcRate, setShowSrcRate] = useState<boolean>(false);

	if (!quoteData || isWrapUnwrapCase(quoteData)) return null;

	const { srcRate, destRate, input, output, estimatedFulfilTime } = quoteData;
	const inputToken = input[0].token;
	const outputToken = output[0].token;

	const multiTokens = output?.length > 1;

	function getRate() {
		if (showSrcRate)
			return <Rate rate={srcRate} tokenOne={inputToken} tokenTwo={outputToken} />;
		return <Rate rate={destRate} tokenOne={outputToken} tokenTwo={inputToken} />;
	}

	// biome-ignore format:
	const dropdownBtnStyle = `bn-flex bn-items-center bn-justify-between bn-pr-4 bn-pl-3 bn-py-3 bn-h-11 bn-border-0 bn-border-b bn-border-dashed ${openDropdown ? 'bn-border-primary': 'bn-border-transparent'}`

	return (
		<motion.div
			className="bn-mt-2 bn-flex-col bn-flex bn-bg-layer-2"
			style={{ borderRadius: getBorderRadius(theme.borderRadius, 8) }}
			layout
		>
			<motion.div layout className={dropdownBtnStyle}>
				{multiTokens ? (
					<BestPriceTag refetch={refetch} />
				) : (
					<div className="bn-flex bn-items-center">
						<RefreshButton onClick={refetch} />
						<button
							type="button"
							className="bn-text-primary bn-text-sm bn-font-medium bn-bg-transparent bn-border-none bn-p-0 bn-cursor-pointer bn-ml-1 bn-aeonik-font"
							onClick={() => setShowSrcRate(!showSrcRate)}
						>
							{getRate()}
						</button>
					</div>
				)}

				<div className="bn-flex bn-items-center bn-text-primary bn-text-sm">
					<TransferType time={estimatedFulfilTime} />
					<button
						type="button"
						onClick={() => setOpenDropdown(!openDropdown)}
						className="bn-bg-transparent bn-border-none bn-p-0 bn-w-5 bn-h-5 bn-ml-1 bn-cursor-pointer bn-text-primary"
					>
						{/* biome-ignore format: */}
						<MIcon name="keyboard_arrow_down" classNames={`bn-transition-transform bn-text-xl bn-h-5 bn-leading-[20px] ${openDropdown ? 'bn-rotate-180' : ''}`}/>
					</button>
				</div>
			</motion.div>

			{openDropdown && (
				<motion.div
					className="bn-px-4 bn-py-3"
					layout
					initial={{ opacity: 0 }}
					animate={{ opacity: 1 }}
				>
					<ReviewSection />
				</motion.div>
			)}
		</motion.div>
	);
};

const BestPriceTag = ({ refetch }: { refetch: () => void }) => {
	return (
		<div className="bn-flex bn-items-center bn-space-x-1">
			<RefreshButton onClick={refetch} />
			<span className="bn-text-primary bn-text-sm bn-aeonik-font bn-font-medium">
				Best Guaranteed Price
			</span>
		</div>
	);
};

const Rate = ({
	rate,
	tokenOne,
	tokenTwo,
}: { rate: number; tokenOne: Token; tokenTwo: Token }) => {
	const locale = useSelector((state: ReduxStateType) => state.settings.language);

	const RateWithTooltip = () => (
		<Tooltip content={rate}>
			<div className="bn-mx-1 bn-inline-block bn-max-w-[60px] bn-overflow-hidden bn-text-ellipsis bn-whitespace-nowrap">
				{adjustDecimals(rate, 4, locale)}
			</div>
		</Tooltip>
	);

	return (
		<div className="bn-flex bn-items-center bn-space-x-1">
			1 {tokenOne.symbol} ~ <RateWithTooltip /> {tokenTwo.symbol}
		</div>
	);
};
