import { omit, upperFirst } from 'lodash';
import React, { HTMLAttributes, useMemo } from 'react';
import { useFormField } from '../../hooks/form';
import { SilkeBox } from '../silke-box';
import { FormFieldProps } from '../silke-form';
import { SilkeIcon } from '../silke-icon';
import styles from './silke-checkbox.scss';
import { generateGuid } from '@vev/utils';

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

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

export function SilkeCheckbox(props: SilkeCheckboxProps) {
  const { name, size, onChange, readOnly, value, style, label, error, onError, id, ...rest } =
    useFormField(props, validate);

  const checkboxId = useMemo(() => {
    return id || `checkbox-${generateGuid()}`;
  }, [id]);

  let cl = styles.container;
  if (readOnly || props.disabled) cl += ' ' + styles.disabled;
  if (error) cl += ' ' + styles.error;
  if (size === 's') cl += ' ' + styles.small;

  const hasLabel = label || name;

  return (
    <SilkeBox tag="div" gap="s" className={cl} align={['start', 'center']} style={style}>
      <input
        {...omit(rest, 'validate', 'placeholder')}
        name={name}
        type="checkbox"
        readOnly={!onChange || readOnly}
        disabled={props.disabled}
        checked={!!value}
        id={checkboxId}
        onChange={(e) => onChange && onChange(e.currentTarget.checked || false)}
      />
      <SilkeBox className={styles.check} align="center">
        <SilkeIcon className={styles.checkmark} icon="check" style={{ fontSize: 12 }} />
      </SilkeBox>
      {hasLabel && (
        <label htmlFor={checkboxId} className={styles.label}>
          {label || upperFirst(name)}
        </label>
      )}
    </SilkeBox>
  );
}
