import React, { FC, useContext } from 'react';
import { SvgDot } from '../../../assets/images/icons';
import { Text } from '../../Text';
import { Context } from '../Context';
import * as sc from './styles';

export interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
  checked?: boolean;
  name?: React.AllHTMLAttributes<HTMLInputElement>['name'];
  label?: React.ComponentType | string;
}

export const Radio: FC<Props> = props => {
  const {
    checked: checkedProp,
    name: nameProp,
    onChange,
    label,
    ...other
  } = props;
  const radioGroup = useContext(Context);
  let checked = checkedProp;
  let name = nameProp;

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (onChange) {
      onChange(event);
    }
    if (radioGroup) {
      radioGroup.onChange(event);
    }
  };

  if (radioGroup) {
    if (typeof checked === 'undefined') {
      checked = radioGroup.value === props.value;
    }
    if (typeof name === 'undefined') {
      name = radioGroup.name;
    }
  }

  return (
    <sc.Wrapper as="label">
      <sc.Input
        type="radio"
        name={name}
        checked={checked}
        onChange={handleChange}
        {...other}
      />
      <sc.Icon
        Asset={SvgDot}
        scale={1}
        width={20}
        height={20}
        color="brandMain"
        checked={checked}
      />
      <Text color="highlightText" ml="s">
        {label}
      </Text>
    </sc.Wrapper>
  );
};
