import { Modal } from "@src/components/Modal";
import { useSwapContext, useTxUIWrapper } from "@src/context";
import { TxStatus } from "@src/models";
import { useCallback, useMemo, useState } from "react";
import { useAccount } from "wagmi";
import { WalletPicker } from "../WalletPicker";

type Button = {
  text: string;
  fn: () => void;
  disabled: boolean;
};

export const SwapButton = () => {
  const { address } = useAccount();
  const { integrationConfig } = useSwapContext();

  const [connectWalletModalOpen, setConnectWalletModalOpen] = useState(false);

  const { error, srcChain, dstChain, srcToken, dstToken, isFetchingRoute } =
    useSwapContext();

  const { setTxStatus, setTxMsg, setTxModalOpen } = useTxUIWrapper();

  const srcChainId = useMemo(() => srcChain?.chainId, [srcChain?.chainId]);
  const dstChainId = useMemo(() => dstChain?.chainId, [dstChain?.chainId]);
  const srcTokenAddress = useMemo(() => srcToken?.address, [srcToken?.address]);
  const dstTokenAddress = useMemo(() => dstToken?.address, [dstToken?.address]);

  const showSwapConfirmationView = useCallback(() => {
    setTxStatus(TxStatus.SWAP_INIT);
    setTxMsg("");
    setTxModalOpen(true);
  }, [setTxModalOpen, setTxMsg, setTxStatus]);

  const button: Button = useMemo(() => {
    if (!srcChainId || !dstChainId || !srcTokenAddress || !dstTokenAddress) {
      return {
        text: "Loading...",
        fn: () => {},
        disabled: true,
      };
    }

    if (error) {
      return {
        text: error,
        fn: () => {},
        disabled: true,
      };
    }

    if (!address) {
      return {
        text: integrationConfig.defaultWalletPicker
          ? "Connect wallet"
          : "Connect wallet first",
        fn: () => {
          setConnectWalletModalOpen(true);
        },
        disabled: !integrationConfig.defaultWalletPicker,
      };
    }

    if (
      srcChainId === dstChainId &&
      srcTokenAddress.toLowerCase() === dstTokenAddress.toLowerCase()
    ) {
      return {
        text: "Change token",
        fn: () => {},
        disabled: true,
      };
    }

    if (!srcTokenAddress || !dstTokenAddress) {
      return {
        text: `Select token`,
        fn: () => {},
        disabled: true,
      };
    }

    if (isFetchingRoute) {
      return {
        text: `Fetching route`,
        fn: () => {},
        disabled: true,
      };
    }

    return {
      text: "Swap",
      fn: async () => {
        showSwapConfirmationView();
      },
      disabled: false,
    };
  }, [
    srcChainId,
    dstChainId,
    srcTokenAddress,
    dstTokenAddress,
    error,
    address,
    isFetchingRoute,
    integrationConfig.defaultWalletPicker,
    showSwapConfirmationView,
  ]);

  return (
    <>
      {connectWalletModalOpen && (
        <Modal onClose={() => setConnectWalletModalOpen(false)}>
          <WalletPicker onClose={() => setConnectWalletModalOpen(false)} />
        </Modal>
      )}

      <button
        type="button"
        disabled={button.disabled}
        onClick={button.fn}
        className={`text-xl leading-5 w-full py-5 cursor-pointer disabled:cursor-not-allowed rounded-x_radius border-none ${
          button.disabled
            ? "bg-t_button_pr_off_bg text-t_button_pr_off_text"
            : "bg-t_button_pr_bg text-t_button_pr_text"
        }`}
      >
        {button.text}
      </button>
    </>
  );
};
