import {
  ArrowDownLongIcon,
  CloseIcon,
  ErrorModalStatusIcon,
  LinkExternalIcon,
  SuccessModalStatusIcon,
} from "@src/assets/icons";
import { useSwapContext, useTxUIWrapper } from "@src/context";
import { TokenItem } from "./TokenItem";
import { useMemo } from "react";
import { Ecosystem } from "@src/models";

type Props = {
  onCloseClick: () => void;
};

export const TxResult = ({ onCloseClick }: Props) => {
  const { txError, txExplorerUrl, txMsg } = useTxUIWrapper();
  const {
    isExpressDeliveryActive,
    srcChain,
    srcToken,
    dstChain,
    dstToken,
    srcValue,
    dstValue,
    bridgeUI,
  } = useSwapContext();

  const value = useMemo(() => {
    if (bridgeUI && srcChain?.ecosystem === Ecosystem.SOLANA) {
      return srcValue;
    }
    return dstValue;
  }, [bridgeUI, srcChain?.ecosystem, srcValue, dstValue]);

  return (
    <div className="flex flex-col gap-5 text-t_text_primary justify-center items-center">
      {txError ? (
        <>
          <div
            className="flex justify-end fill-t_text_primary cursor-pointer w-full"
            onClick={onCloseClick}
          >
            <CloseIcon className="w-3.5 h-3.5" />
          </div>
          <ErrorModalStatusIcon />
          <div className="text-2xl font-bold">Transaction failed</div>
          <div className="text-center">{txError}</div>
        </>
      ) : (
        <>
          <div
            className="flex justify-end fill-t_text_primary cursor-pointer w-full"
            onClick={onCloseClick}
          >
            <CloseIcon className="w-3.5 h-3.5" />
          </div>
          <SuccessModalStatusIcon />
          <div className="flex flex-col items-center">
            <div className="text-2xl font-bold">Transaction success!</div>
            {!txMsg && srcChain !== dstChain && (
              <div className="text-sm font-normal opacity-60">
                {`Approximated time of delivery: ${
                  isExpressDeliveryActive ? "30 sec" : "30 min"
                }`}
              </div>
            )}
          </div>
          {!txMsg && (
            <div className="flex items-center gap-2">
              <TokenItem chain={srcChain} token={srcToken} value={srcValue} />
              <div className="-rotate-90 flex justify-center w-8 fill-t_text_primary opacity-50">
                <ArrowDownLongIcon />
              </div>
              <TokenItem chain={dstChain} token={dstToken} value={value} />
            </div>
          )}
          <a
            href={txExplorerUrl}
            target="_blank"
            rel="noreferrer"
            className="flex gap-4 items-center mb-2 fill-t_main_accent_light"
          >
            <p className="text-t_text_secondary underline">
              View details on Explorer
            </p>
            <LinkExternalIcon />
          </a>
        </>
      )}
    </div>
  );
};
