import React, { LegacyRef } from 'react';
import classNames from 'classnames';
import InputGroupWithRef, { InputGroupProps } from './InputGroup';
import { FormDefaults } from '../FormDefaults';

// TODO: make className tailwind-able instead of css. make it typeof string ????
// or should we just give a div a className and let each project decide? (this seems to be the patern)
export interface IconInputGroupProps
  extends Omit<
    InputGroupProps<string | undefined | null>,
    'onChange' | 'type' | 'value'
  > {
  type?: 'color' | 'email' | 'search' | 'tel' | 'text' | 'url';
  /** Icon to display on the input group. */
  icon: React.ReactNode;
  /** Text to display after the input group to give more information to the user. */
  helpText?: string;
}

function IconInputGroup(
  { icon, className, ...rest }: IconInputGroupProps,
  ref: LegacyRef<HTMLInputElement>
) {
  const { input } = rest;

  return (
    <>
      <InputGroupWithRef
        icon={icon}
        ref={ref}
        className={classNames(
          className,
          FormDefaults.cssClassPrefix + 'icon-input-group'
        )}
        value={input.value ?? ''}
        onChange={(e) => {
          if (!e.target.value) {
            input.onChange(undefined);
          } else {
            input.onChange(e.target.value);
          }
        }}
        {...rest}
      />
    </>
  );
}

/** Input group with an icon. */
const IconInputGroupWithRef = React.forwardRef(
  IconInputGroup
) as React.ComponentType<IconInputGroupProps>;

export default IconInputGroupWithRef;
