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 { RadioIcon } from './radio-icon';
import { RadioContext } from './radio.context';
import { IRadioVariants, radioVariants } from './radio.variants';

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

const StyledRadioInput = styled(Ariakit.Radio) <RadioProps>`
  ${props => getVariantKey('input', props.variant, props.variants)}
`;

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

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

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

export type RadioComponent<C extends React.ElementType = 'input'> = UIComponentWithRef<C, Ariakit.RadioProps & Props>;

export const Radio: RadioComponent = forwardRef<HTMLInputElement, RadioProps>(
  function Radio({
    className,
    variant = 'default',
    variants,
    ...props
  }, ref) {
    const context = useContext(RadioContext);
    const classNames = getClassNames('radio', className);
    const globalVariants = useVariants('radio', radioVariants);
    variants = variants || globalVariants;
    return (
      <StyledRadio
        className={classNames}
        variant={variant || context?.variant}
        variants={variants || context?.variants}
      >
        <StyledRadioInput
          className="radio__input"
          ref={ref}
          variant={variant || context?.variant}
          variants={variants || context?.variants}
          {...props}
        />
        <StyledRadioIcon
          className="radio__icon"
          variant={variant || context?.variant}
          variants={variants || context?.variants}
          aria-hidden="true"
        />
      </StyledRadio>
    );
  }
);
