import React, { HTMLAttributes } from 'react';
import { FormFieldProps } from '../silke-form';
import { useFormField } from '../../hooks/form';
import { SilkeBox } from '../silke-box';
import styles from './silke-toggle.scss';
import { SilkeText } from '../silke-text';

type Props = FormFieldProps<boolean> &
  Omit<HTMLAttributes<HTMLInputElement>, 'onChange' | 'checkbox' | 'value' | 'style'> & {
    disabled?: boolean;
    /** Invert when toggle is on, so if false the toggle is on */
    invert?: boolean;
    required?: boolean;
    small?: boolean;
    help?: React.ReactNode;
  };

function validate(props: Props, value?: boolean) {
  if (props.required && !value) return 'Required';
}

export function SilkeToggle(props: Props) {
  const {
    small,
    disabled,
    invert,
    name,
    onChange,
    readOnly,
    value,
    onFocus,
    onBlur,
    label,
    error,
    help,
  } = useFormField(props, validate);

  const cl = [styles.container];
  if (disabled) cl.push(styles.disabled);
  if (small) cl.push(styles.small);
  if (error) cl.push(styles.error);

  return (
    <SilkeBox tag="label" column gap="s" hAlign="start" vAlign="center" className={cl.join(' ')}>
      <input
        type="checkbox"
        onFocus={onFocus}
        onBlur={onBlur}
        name={name}
        readOnly={!onChange || readOnly}
        disabled={disabled}
        checked={invert ? !value : value}
        onChange={(e) =>
          onChange &&
          onChange(invert ? !(e.currentTarget.checked || false) : e.currentTarget.checked || false)
        }
      />
      {label && <SilkeText weight="strong">{label}</SilkeText>}
      {help && (
        <SilkeText tag="span" flex color="neutral-80">
          {help}
        </SilkeText>
      )}
      <div className={styles.switch} />
    </SilkeBox>
  );
}
