import React, { useCallback } from 'react';
import { clsx } from 'clsx';

import { forwardRef } from '../utils/react';
import { Box } from '../box';
import * as css from './input-container.css';

/*-- Types --*/

export interface InputAddonProps
  extends Pick<css.InputAddonVariants, 'pointerEvents'> {}

export interface InputContainerProps extends css.InputContainerVariants {
  startAddon?: React.ReactNode;
  startAddonProps?: InputAddonProps;
  endAddon?: React.ReactNode;
  endAddonProps?: InputAddonProps;
  startAddonRef?: React.ForwardedRef<HTMLDivElement>;
  endAddonRef?: React.ForwardedRef<HTMLDivElement>;
}

/*-- Main --*/

export const InputContainer = forwardRef<'div', InputContainerProps>(
  function InputContainer(
    {
      children,
      className,
      disabled,
      focused,
      full,
      startAddon,
      startAddonProps,
      endAddon,
      endAddonProps,
      startAddonRef,
      endAddonRef,
      ...rest
    },
    ref,
  ) {
    const cn = clsx(className, css.inputContainer({ disabled, focused, full }));

    const onAddonMouseDown: React.MouseEventHandler<HTMLDivElement> =
      useCallback(event => {
        // Prevent focus lose from input on clicking addon.
        event.preventDefault();
      }, []);

    return (
      <Box ref={ref} className={cn} {...rest}>
        {startAddon && (
          <div
            ref={startAddonRef}
            className={css.inputAddon({
              position: 'start',
              ...startAddonProps,
            })}
            onMouseDown={onAddonMouseDown}
          >
            {startAddon}
          </div>
        )}
        {children}
        {endAddon && (
          <div
            ref={endAddonRef}
            className={css.inputAddon({ position: 'end', ...endAddonProps })}
            onMouseDown={onAddonMouseDown}
          >
            {endAddon}
          </div>
        )}
      </Box>
    );
  },
);
