import { getClassNames } from '@websolutespa/bom-core';
import { forwardRef, useState } from 'react';
import styled from 'styled-components';
import { UIComponentWithRef, UIStyledComponentProps } from '../../components/types';
import { getCssResponsive } from '../../components/utils';
import { getVariant, useVariants } from '../../variants';
import { ITextareaVariants, textareaVariants } from './textarea.variants';

type Props = {
  variant?: keyof typeof textareaVariants | (string & {});
  variants?: ITextareaVariants;
};

export type TextAreaProps = UIStyledComponentProps<Props, 'textarea'>;

export type TextAreaComponent<C extends React.ElementType = 'textarea'> = UIComponentWithRef<C, Props>;

const StyledTextArea = styled.div<TextAreaProps>`
  ${props => getVariant(props.variant, props.variants)}
  ${props => getCssResponsive(props)}
`;

export const TextArea: TextAreaComponent = forwardRef(({
  as = 'textarea',
  children,
  className,
  onFocus,
  onBlur,
  variant = 'default',
  variants,
  ...props
}, ref) => {
  const [focus, setFocus] = useState<boolean>(false);
  const onFocus_ = (event: React.FocusEvent<HTMLInputElement>) => {
    onFocus && onFocus(event);
    setFocus(true);
  };
  const onBlur_ = (event: React.FocusEvent<HTMLInputElement>) => {
    onBlur && onBlur(event);
    setFocus(false);
  };
  const classNames = getClassNames('textarea', {
    focus,
    disabled: props.disabled,
    readonly: props.readOnly,
    hidden: props.hidden,
  }, className, variant);
  const globalVariants = useVariants('textarea', textareaVariants);
  variants = variants || globalVariants;
  return (
    <StyledTextArea
      className={classNames}
      ref={ref}
      as={as}
      onFocus={onFocus_}
      onBlur={onBlur_}
      variant={variant}
      variants={variants}
      {...props}
    >
      {children}
    </StyledTextArea>
  );
});

TextArea.displayName = 'TextArea';
