import { useCallback } from 'react';

import type { FC } from 'react';
import type { TextInputProps } from '.';

import TextInput from '.';
import Gradient from '../Gradient';
import Loading from '../Loading';

export interface TextInputWithLoadingProps extends TextInputProps {
  isLoading?: boolean;
}

const NOOP = () => null;

const TextInputWithLoading: FC<TextInputWithLoadingProps> = ({
  isLoading,
  renderAfter = NOOP,
  ...textInputProps
}) => {
  return (
    <TextInput
      {...textInputProps}
      renderAfter={useCallback(
        (params) => {
          const { background } = params;

          if (isLoading) {
            return (
              <Gradient
                flexBox
                justifyEnd
                alignCenter
                fullHeight
                // when the text is centered we position this content absolute
                // so that it doesn't push the text off-center to the left
                positionAbsolute={textInputProps.centerText}
                pointerEvents="none"
                right={0}
                top={0}
                to="transparent"
                from={background}
                endAt="20%"
                angle={90}
                padding="0 .8em"
              >
                <Loading size="1.115em" />
              </Gradient>
            );
          }

          return renderAfter(params);
        },
        [isLoading, renderAfter, textInputProps.centerText]
      )}
      withTracking
    />
  );
};

export default TextInputWithLoading;
