import { useSelector } from "react-redux";

import type { FormattedQuoteResponse } from "@hooks/apis/common/quote/types";
import { isAutoQuote, isManualQuote } from "@hooks/apis/common/quote/useQuote";
import { useTheme } from "@hooks/useTheme";
import type { ReduxStateType } from "@store/types";
import { adjustDecimals } from "@utils/adjustDecimals";
import { formatValue } from "@utils/formatValue";
import { getBorderRadius } from "@utils/getBorderRadius";
import { getTimeInMins } from "@utils/getTimeInMins";
import { Fragment } from "react/jsx-runtime";
import { MIcon } from "../MIcon";
import { AutoTag } from "./utils/AutoTag";
import { Dot } from "./utils/Dot";
import { Fees } from "./utils/Fees";
import { RouteProtocol } from "./utils/RouteProtocol";
import { RouteTag, tagsInfo } from "./utils/RouteTag";

type RouteItemType = {
  route: FormattedQuoteResponse;
  onClick: () => void;
  isActive: boolean;
  tags?: Array<"best" | "fast">;
  bestRoute?: FormattedQuoteResponse;
  variant?: boolean;
};

export const ComparisonItem = ({
  route,
  bestRoute,
  onClick,
  isActive,
  tags,
  variant,
}: RouteItemType) => {
  const theme = useTheme();
  const locale = useSelector(
    (state: ReduxStateType) => state.settings.language
  );
  // biome-ignore format:
  const style = `${
    isActive
      ? "bn-bg-accent-1 bn-border-theme"
      : "bn-bg-layer-2 bn-border-transparent"
  } bn-flex bn-justify-between bn-items-center bn-border bn-border-solid bn-px-4 bn-py-[14px] bn-flex-1 bn-cursor-pointer bn-w-full`;

  const { primaryOutput, estimatedFulfilTime, isSwapRoute } = route;
  const toAmount = primaryOutput.amount;
  const toToken = primaryOutput.token;

  const isFastestRoute = tags?.includes("fast") ?? false;

  const routeOutputInUsd =
    route?.primaryOutput?.effectiveReceivedInUsd ||
    route?.primaryOutput?.valueInUsd;
  const bestRouteOutputInUsd =
    bestRoute?.primaryOutput?.effectiveReceivedInUsd ||
    bestRoute?.primaryOutput?.valueInUsd;
  const priceDiff = (() => {
    if (routeOutputInUsd && bestRouteOutputInUsd) {
      return bestRouteOutputInUsd - routeOutputInUsd;
    }
    return 0;
  })();

  const renderRouteInfo = () => {
    if (isAutoQuote(route)) {
      return (
        <div className="bn-flex bn-items-center bn-space-x-2">
          <AutoTag active classNames="bn-rounded-full" />
          {priceDiff > 0 && (
            <span className="bn-text-sm bn-font-medium bn-text-accent-4">
              -${adjustDecimals(priceDiff, 2, locale)}
            </span>
          )}
        </div>
      );
    }

    if (priceDiff > 0)
      return (
        <span className="bn-text-sm bn-font-medium bn-text-accent-4">
          -${adjustDecimals(priceDiff, 2, locale)}
        </span>
      );

    if (tags?.length) {
      return (
        <div className="bn-flex bn-items-center bn-space-x-2 bn-mb-1">
          {tags
            .filter((item) => item === "best")
            .map((item) => (
              <RouteTag item={tagsInfo[item]} isActive={isActive} key={item} />
            ))}
        </div>
      );
    }

    return <></>;
  };

  const routeInfo = [
    primaryOutput?.valueInUsd ? (
      <p
        className="bn-text-secondary bn-text-sm bn-text-left bn-leading-[14px]"
        key={1}
      >
        ${adjustDecimals(primaryOutput.valueInUsd, 2, locale)}
      </p>
    ) : undefined,
    isManualQuote(route) ? (
      <RouteProtocol
        routeDetails={isManualQuote(route) ? route.protocol : undefined}
        key={2}
      />
    ) : undefined,
  ];

  return (
    <button
      type="button"
      className={style}
      onClick={onClick}
      style={{ borderRadius: getBorderRadius(theme.borderRadius, 8) }}
    >
      <div className="bn-aeonik-font bn-flex bn-space-y-1 bn-flex-col">
        <p className="bn-text-base bn-font-medium bn-text-primary bn-text-left bn-leading-[18px]">
          {adjustDecimals(formatValue(toAmount, toToken.decimals), 3, locale)}{" "}
          {toToken.symbol}
        </p>
        <div className="bn-flex bn-items-center bn-space-x-2">
          {routeInfo
            .filter((arrItem) => arrItem !== undefined)
            .map((item, index, arr) => (
              <Fragment key={`item-${item.key}`}>
                {item}
                {index < arr.length - 1 && <Dot key={`dot-${item.key}`} />}
              </Fragment>
            ))}
        </div>
      </div>

      <div className="bn-flex bn-flex-col bn-items-end">
        {renderRouteInfo()}

        {/* biome-ignore format:  */}
        <div
          className={`bn-flex bn-space-x-1 bn-font-medium bn-text-sm ${
            variant ? "bn-flex-col bn-items-end" : "bn-flex-row bn-items-center"
          }`}
        >
          <Fees route={route} noDot={variant} />

          {estimatedFulfilTime && !isSwapRoute && (
            <>
              <Dot />
              {/* biome-ignore format:  */}
              <span
                className={`bn-aeonik-font bn-flex bn-items-center ${
                  isFastestRoute ? "bn-text-accent-3" : "bn-text-secondary"
                }`}
              >
                {getTimeInMins(estimatedFulfilTime).fullShort}
                {isFastestRoute && (
                  <MIcon
                    name="bolt"
                    classNames="bn-text-sm bn-text-sucess bn-ml-0.5"
                  />
                )}
              </span>
            </>
          )}
        </div>
      </div>
    </button>
  );
};
