import React, { useEffect, useState } from 'react';
import { clsx } from 'clsx';

import { forwardRef } from '../utils/react';
import { FieldLabel, FieldLabelProps } from '../field-label';
import * as css from './input-label.css';

export interface InputLabelProps extends FieldLabelProps {
  shrinked?: boolean;
}

/**
 * A floating label for Input. It depends on `InputContainer` and intented to be
 * used with it.
 */
export const InputLabel = forwardRef<'label', InputLabelProps>(
  function InputLabel({ className, children, shrinked, ...rest }, ref) {
    const [isAnimated, setIsAnimated] = useState(false);

    useEffect(() => {
      // We initially turn off the animation of label until the component
      // renders for the first time. After that we re-enable it in the next
      // paint frame.
      requestAnimationFrame(() => {
        setTimeout(() => {
          setIsAnimated(true);
        }, 0);
      });
    }, []);

    const cn = clsx(className, css.label({ animated: isAnimated, shrinked }));

    return (
      <FieldLabel ref={ref} className={cn} {...rest}>
        {children}
      </FieldLabel>
    );
  },
);
