import * as Ariakit from '@ariakit/react';
import { getClassNames } from '@websolutespa/bom-core';
import { forwardRef, useContext } from 'react';
import styled from 'styled-components';
import { UIComponentWithRef, UIStyledComponentProps } from '../../components/types';
import { getCssResponsive } from '../../components/utils';
import { getVariantKey, useVariants } from '../../variants';
import { CheckboxIcon } from './checkbox-icon';
import { CheckboxContext } from './checkbox.context';
import { checkboxVariants, ICheckboxVariants } from './checkbox.variants';

const StyledCheckbox = styled.div<Props>`
  ${props => getVariantKey('checkbox', props.variant, props.variants)}
  ${props => getCssResponsive(props)}
`;

const StyledCheckboxInput = styled(Ariakit.Checkbox) <CheckboxProps>`
  ${props => getVariantKey('input', props.variant, props.variants)}
`;

const StyledCheckboxIcon = styled(CheckboxIcon) <Props>`
  ${props => getVariantKey('icon', props.variant, props.variants)}
`;

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

export type CheckboxProps = Ariakit.CheckboxProps & UIStyledComponentProps<Props, 'input'>;

export type CheckboxComponent<C extends React.ElementType = 'input'> = UIComponentWithRef<C, Props>;

export const Checkbox: CheckboxComponent = forwardRef<HTMLInputElement, CheckboxProps>(
  function Checkbox({
    className,
    variant = 'default',
    variants,
    ...props
  }, ref) {
    const context = useContext(CheckboxContext);
    const classNames = getClassNames('checkbox', className);
    const globalVariants = useVariants('checkbox', checkboxVariants);
    variants = variants || globalVariants;
    return (
      <StyledCheckbox
        className={classNames}
        variant={variant || context?.variant}
        variants={variants || context?.variants}
      >
        <StyledCheckboxInput
          className="checkbox__input"
          ref={ref}
          variant={variant || context?.variant}
          variants={variants || context?.variants}
          {...props}
        />
        <StyledCheckboxIcon
          className="checkbox__icon"
          variant={variant || context?.variant}
          variants={variants || context?.variants}
          aria-hidden="true"
        />
      </StyledCheckbox>
    );
  }
);
