import type { TokenAmount } from '@lifi/sdk';
import { Box, FormHelperText, Skeleton, Typography } from '@mui/material';
import { useTranslation } from 'react-i18next';
import { useTokenAddressBalance } from '../../hooks/useTokenAddressBalance.js';
import type { FormTypeProps } from '../../stores/form/types.js';
import { FormKeyHelper } from '../../stores/form/types.js';
import { useFieldValues } from '../../stores/form/useFieldValues.js';
import { formatTokenAmount, formatTokenPrice } from '../../utils/format.js';
import { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';
import { useAvailableChains } from '../../hooks/useAvailableChains.js';
import { useFieldActions } from '../../stores/form/useFieldActions.js';
import { formatUnits } from 'viem';
import { useGasRecommendation } from '../../hooks/useGasRecommendation.js';

export const PriceFormHelperTextCustom = ({ formType, route }: any) => {
  const [chainId, tokenAddress] = useFieldValues(
    FormKeyHelper.getChainKey(formType),
    FormKeyHelper.getTokenKey(formType),
  );
  const { token, isLoading } = useTokenAddressBalance(chainId, tokenAddress);

  return (
    <PriceFormHelperTextBase
      formType={formType}
      isLoading={isLoading}
      tokenAddress={tokenAddress}
      token={token as any}
      route={route}
    />
  );
};

export const PriceFormHelperTextBase: React.FC<
  FormTypeProps & {
    isLoading?: boolean;
    tokenAddress?: string;
    token?: TokenAmount;
    route?: any;
  }
> = ({ formType, isLoading, tokenAddress, token, route }) => {
  const { t } = useTranslation();
  const [amount] = useFieldValues(FormKeyHelper.getAmountKey(formType));
  const { setFieldValue } = useFieldActions();
  const [chainId] = useFieldValues(
    FormKeyHelper.getChainKey(formType),
    FormKeyHelper.getTokenKey(formType),
  );

  const { subvariant } = useWidgetConfig();

  const routeToken =
    subvariant === 'custom'
      ? { ...route?.fromToken, amount: BigInt(route?.fromAmount || 0) }
      : { ...route?.toToken, amount: BigInt(route?.toAmount || 0) };

  const tokenAmount = formatTokenAmount(routeToken.amount, routeToken.decimals);

  const fromAmountTokenPrice =
    formType === 'from'
      ? formatTokenPrice(amount, token?.priceUSD)
      : formatTokenPrice(tokenAmount, token?.priceUSD);

  const { getChainById } = useAvailableChains();
  const { data } = useGasRecommendation(chainId);

  const handleMax = () => {
    if (!token?.amount) {
      return;
    }
    const chain = getChainById(chainId);
    let maxAmount = token.amount;
    if (
      chain?.nativeToken.address === tokenAddress &&
      data?.available &&
      data?.recommended
    ) {
      const recommendedAmount = BigInt(data.recommended.amount || 0) / 2n;
      if (token.amount > recommendedAmount) {
        maxAmount = token.amount - recommendedAmount;
      }
    }
    if (maxAmount) {
      setFieldValue(
        FormKeyHelper.getAmountKey(formType),
        formatUnits(maxAmount, token.decimals),
        {
          isTouched: true,
        },
      );
    }
  };

  return (
    <FormHelperText
      component="div"
      sx={{
        display: 'flex',
        justifyContent: 'space-between',
        margin: 0,
        marginLeft: 2,
        marginTop: 0.75,
      }}
    >
      <Typography
        component="span"
        color="text.secondary"
        fontWeight={500}
        fontSize={12}
        lineHeight={1}
        flex={1}
        sx={{
          wordBreak: 'break-word',
          overflowWrap: 'break-word',
        }}
      >
        {t(`format.currency`, {
          value: fromAmountTokenPrice,
        })}
      </Typography>

      {formType === 'from' ? (
        <>
          {isLoading && tokenAddress ? (
            <Skeleton variant="text" width={48} height={12} />
          ) : token?.amount ? (
            <Box onClick={handleMax}>
              <Box
                component="span"
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  color: (theme) => theme.palette.text.secondary,
                  fontWeight: 500,
                  fontSize: 12,
                  lineHeight: 1,
                  paddingLeft: 0.25,
                }}
              >
                {`/`}
                <Box
                  component="span"
                  sx={{
                    color: (theme) => theme.palette.text.secondary,
                    fontWeight: 500,
                    fontSize: 12,
                    lineHeight: 1,
                    paddingLeft: 0.25,
                    textDecoration: 'underline',
                    cursor: 'pointer',
                    width: 'max-content',
                  }}
                >
                  {t(`format.number`, {
                    value: formatTokenAmount(token.amount, token.decimals),
                  })}
                </Box>
              </Box>
            </Box>
          ) : null}
        </>
      ) : null}
    </FormHelperText>
  );
};
