import * as Ariakit from '@ariakit/react';
import { FormLabel, useFormContext } from '@ariakit/react';
import { getClassNames } from '@websolutespa/bom-core';
import { forwardRef, ReactNode } from 'react';
import styled from 'styled-components';
import { UIStyledComponentProps } from '../../components/types';
import { getCssResponsive } from '../../components/utils';
import { getVariant, useVariants } from '../../variants';
import { ILabelVariants, labelVariants } from './label.variants';

const StyledLabel = styled.label<LabelProps>`
  ${props => getVariant(props.variant, props.variants)}
  ${props => getCssResponsive(props)}
`;

export type LabelProps = Omit<Ariakit.FormLabelProps, 'name'> & UIStyledComponentProps<{
  className?: string;
  variant?: keyof typeof labelVariants | (string & {});
  variants?: ILabelVariants;
  children?: ReactNode;
  htmlFor?: string;
  name?: string;
}>;

export const Label = forwardRef<HTMLLabelElement, LabelProps>(
  function Label({
    className,
    name,
    htmlFor,
    variant = 'default',
    variants,
    ...props }, ref) {
    name = name || htmlFor;
    const form = useFormContext();
    const classNames = getClassNames('label', className, variant);
    const globalVariants = useVariants('label', labelVariants);
    variants = variants || globalVariants;
    return form && name ? (
      <FormLabel name={name} render={(
        <StyledLabel className={classNames} ref={ref} variant={variant} variants={variants} {...props} />
      )} />
    ) : (
      <StyledLabel htmlFor={name} className={classNames} ref={ref} variant={variant} variants={variants} {...props} />
    );
  });
