import { LoadingButton } from '@mui/lab';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
// import { useEffect, useRef } from 'react';
import { useRef } from 'react';
import { useAccount } from '../../hooks/useAccount.js';
import { useChain } from '../../hooks/useChain.js';
import { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';
import { useFieldValues } from '../../stores/form/useFieldValues.js';
import { navigationRoutes } from '../../utils/navigationRoutes.js';
import type { BaseTransactionButtonProps } from './types.js';
import { useFromTokenSufficiency } from '../../hooks/useFromTokenSufficiency.js';
import { useGasSufficiency } from '../../hooks/useGasSufficiency.js';
import { useRoutes } from '../../hooks/useRoutes.js';

export const BaseTransactionButton: React.FC<BaseTransactionButtonProps> = ({
  onClick,
  text,
  disabled,
  loading,
}) => {
  const loadingButtonRef = useRef<HTMLButtonElement>(null);
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { walletConfig } = useWidgetConfig();
  const [fromChainId] = useFieldValues('fromChain');
  const [fromAmount] = useFieldValues('fromAmount');
  const { chain } = useChain(fromChainId);
  const { account } = useAccount({ chainType: chain?.chainType });
  const { routes } = useRoutes();
  const currentRoute = routes?.[0];
  const { insufficientGas } = useGasSufficiency(currentRoute);
  const { insufficientFromToken } = useFromTokenSufficiency(currentRoute);

  // useEffect(() => {
  //   // it's for moewbie case when the button is not visible
  //   if (text === t('button.swapReview') && loadingButtonRef.current) {
  //     loadingButtonRef.current.scrollIntoView({ behavior: 'smooth' });
  //   }
  // }, [t, text]);

  const handleClick = async () => {
    if (account.isConnected) {
      onClick?.();
    } else if (walletConfig?.onConnect) {
      walletConfig.onConnect();
    } else {
      navigate(navigationRoutes.selectWallet);
    }
  };

  const getButtonText = () => {
    if (account.isConnected) {
      if (text && text !== 'Review swap') {
        return text;
      } else {
        return 'Swap';
      }
    }
    return t(`button.connectWallet`);
  };

  return (
    <LoadingButton
      ref={loadingButtonRef}
      variant="contained"
      color="primary"
      onClick={handleClick}
      disabled={
        fromAmount.length !== 0 &&
        ((account.isConnected && disabled) ||
          insufficientFromToken ||
          insufficientGas?.length !== 0)
      }
      loading={loading}
      loadingPosition="center"
      fullWidth
    >
      {getButtonText()}
    </LoadingButton>
  );
};
