import clsx from 'clsx';
import { twMerge } from 'tailwind-merge';

export type Props = React.HTMLAttributes<HTMLDivElement> & {
  okayClassName?: string;
  warningClassName?: string;
  errorClassName?: string;
  length: number;
  visibleThreshold?: number;
  visibleLength?: number;
  warningThreshold?: number;
  warningLength?: number;
  maxLength: number;
};

const CharacterCount: React.FC<Props> = (props) => {
  const {
    className,
    okayClassName = 'text-inherit',
    errorClassName = 'text-accent-error-on-primary',
    warningClassName = errorClassName,
    length = 0,
    maxLength = Infinity,
    visibleThreshold = 0,
    visibleLength = visibleThreshold * maxLength,
    warningThreshold = 1,
    warningLength = warningThreshold * maxLength,
    ...restProps
  } = props;
  return (
    <div
      className={twMerge(
        clsx(
          'font-sans text-sm transition-opacity duration-100',
          okayClassName,
          {
            'opacity-0': length < visibleLength,
            [warningClassName]: length >= warningLength,
          },
          { [errorClassName]: length > maxLength }
        ),
        className
      )}
      {...restProps}
    >
      {length} / {maxLength === Infinity ? '∞' : maxLength}
    </div>
  );
};
export default CharacterCount;
