import React, { useState } from 'react';
import { useTheme } from '@emotion/react';
import { capitalize } from '../../functions';
import { StyledRadio } from './style';
import { ErrorMessage } from '../ErrorMessage';

export interface Props {
  value: string | number;
  checked?: boolean;
  setChecked?: (val: unknown) => void;
  label?: string;
  width?: number;
  error?: string;
  sizer?: 'M' | 'S';
}
export const Radio = ({
  value,
  checked,
  setChecked,
  label = '',
  sizer = 'S',
  width = 20,
  error,
  ...props
}: Props) => {
  const colors = useTheme();
  const [visited, setVisited] = useState<boolean>(false);
  return (
    <>
      <StyledRadio
        active={checked as boolean}
        theme={{ ...colors }}
        width={width}
      >
        <div className={`${sizer}`}>{capitalize(label)}</div>
        <input
          value={value}
          type="radio"
          onClick={(e) => {
            if (setChecked) {
              setChecked(value);
            }
          }}
          {...props}
          onBlur={() => setVisited(true)}
        />
        <span className={`checkmark ${visited && error ? 'error' : ''}`}></span>
      </StyledRadio>
      {visited && <ErrorMessage error={error || ''} />}
    </>
  );
};
