import { Box, useMediaQuery, type BoxProps, type Theme } from '@mui/material';
import { ReverseTokensButton } from '../ReverseTokensButton/ReverseTokensButton.js';
import { ReverseTokensButtonEmpty } from '../ReverseTokensButton/ReverseTokensButton.style.js';
import { useFieldValues } from '../../stores/form/useFieldValues.js';
import { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';
import { DisabledUI, HiddenUI } from '../../types/widget.js';
import { AmountInput } from '../AmountInputCustom/AmountInput.js';

export const SelectChainAndTokenCustom: React.FC<BoxProps> = (props) => {
  const { subvariant, hiddenUI, disabledUI } = useWidgetConfig();

  const prefersNarrowView = useMediaQuery((theme: Theme) =>
    theme.breakpoints.down('sm'),
  );

  const [fromChain, toChain, fromToken, toToken] = useFieldValues(
    'fromChain',
    'toChain',
    'fromToken',
    'toToken',
  );

  const hiddenToToken =
    subvariant === 'custom' || hiddenUI?.includes(HiddenUI.ToToken);

  const hiddenReverse =
    subvariant === 'refuel' ||
    disabledUI?.includes(DisabledUI.FromToken) ||
    disabledUI?.includes(DisabledUI.ToToken) ||
    hiddenUI?.includes(HiddenUI.ToToken);

  const isCompact =
    !!fromChain &&
    !!toChain &&
    !!fromToken &&
    !!toToken &&
    !prefersNarrowView &&
    !hiddenToToken;

  const custom = subvariant === 'custom';

  return (
    <>
      {!custom ? (
        <Box display="flex" flexDirection="column" sx={{ marginBottom: 2 }}>
          <AmountInput formType="from" />

          {!hiddenToToken ? (
            !hiddenReverse ? (
              <ReverseTokensButton vertical={!isCompact} isCustom={true} />
            ) : (
              <ReverseTokensButtonEmpty />
            )
          ) : null}

          <AmountInput formType="to" />
        </Box>
      ) : null}
    </>
  );
};
