import { SilkeBox } from '../silke-box';
import { FormFieldProps, FormValidator } from '../silke-form';
import { useFormField } from '../../hooks/form';
import { upperFirst, omit } from 'lodash';
import React, { HTMLAttributes, useMemo } from 'react';
import styles from './silke-radio-button.scss';
import { generateGuid } from '@vev/utils';
import cx from 'classnames';

type SilkeRadioButtonProps = FormFieldProps<any> &
  Omit<HTMLAttributes<HTMLInputElement>, 'onChange' | 'checkbox' | 'value' | 'style'> & {
    disabled?: boolean;
    required?: boolean;
    style?: React.CSSProperties;
    size?: 'micro' | 'small' | 'base' | 'large';
  };

const validate: FormValidator<SilkeRadioButtonProps> = (props, value?: boolean) => {
  if (props.required && value === undefined) return 'Required';
};

export function SilkeRadioButton(props: SilkeRadioButtonProps) {
  const { name, onChange, readOnly, value, style, label, error, onError, ...rest } = useFormField(
    props,
    validate,
  );
  let cl = styles.container;
  if (readOnly || props.disabled) cl += ' ' + styles.disabled;
  if (error) cl += ' ' + styles.error;

  const inputId = useMemo(() => {
    return rest.id || 'radio-' + generateGuid();
  }, []);

  // NB props.value is not same as useFormField value as this comes from form context
  return (
    <SilkeBox gap="s" className={cl} align={['start', 'center']} style={style}>
      <input
        {...omit(rest, ['validate', 'placeholder', 'size'])}
        id={inputId}
        name={name}
        type="radio"
        readOnly={!onChange || readOnly}
        disabled={props.disabled}
        checked={props.value === value}
        value={props.value}
        onChange={() => onChange && onChange(props.value)}
      />
      <div className={styles.circle} />
      <label
        className={cx(styles.label, {
          [styles.micro]: props.size === 'micro',
          [styles.small]: props.size === 'small',
          [styles.base]: props.size === 'base',
          [styles.large]: props.size === 'large',
        })}
        htmlFor={inputId}
      >
        {label}
      </label>
    </SilkeBox>
  );
}
