
import { getClassNames } from '@websolutespa/bom-core';
import { ComponentPropsWithRef, forwardRef } from 'react';
import styled from 'styled-components';
import { UIComponentWithRef, UIStyledComponentProps } from '../../components/types';
import { getCssResponsive } from '../../components/utils';
import { SizeVariant } from '../../variants';
import { RadioIcon } from './radio-icon';

type Props = Omit<ComponentPropsWithRef<'input'>, 'size'> & {
  size?: SizeVariant;
};

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

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

const StyledRadioInput = styled.div`
  appearance: none;
  position: absolute;
  opacity: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  cursor: pointer;

  &:disabled {
    cursor: not-allowed;
  }
`;

const StyledRadioIcon = styled.div`
  border-radius: 50%;
  pointer-events: none;
  outline: 2px solid transparent;
  outline-offset: 2px;
  transition: outline-color 150ms ease-in 0s, color 200ms ease-out 0s;
  color: var(--form-border-color-hover);

  input:checked ~ & {
    color: var(--form-outline-color-active);
  }

  input:not(:disabled):hover ~ & {
    outline-color: var(--form-border-color-hover);
  }

  input:focus ~ & {
    outline-color: var(--form-outline-color-focus);
  }
`;

const StyledRadio = styled.div`
  position: relative;
  margin-right: 0.5rem;
  ${props => getCssResponsive(props)}
`;

export const RadioBase: RadioComponent = forwardRef(({ as = 'input', className, ...props }, ref) => {
  const classNames = getClassNames('radio', className);
  return (
    <StyledRadio className={classNames}>
      <StyledRadioInput ref={ref} as={as} type="radio" {...props} />
      <StyledRadioIcon as={RadioIcon} aria-hidden="true" />
    </StyledRadio>
  );
});

RadioBase.displayName = 'Radio';
