import React, { FC, InputHTMLAttributes } from 'react';
import { InlineFlex } from '../InlineFlex';
import { SvgCheckmark } from '../../assets/images/icons';
import * as typeHelpers from '../../typings/helpers';
import * as sc from './styles';
import { Label } from './Label';

export interface Props
  extends typeHelpers.Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange'> {
  onChange: (e: boolean) => void;
  /**
   * Specify whether the toggle should be on by default
   */
  defaultChecked?: boolean;
  /**
   * Specify whether the control is checked
   */
  checked?: boolean;
  name?: React.AllHTMLAttributes<HTMLInputElement>['name'];
  label?: React.ComponentType | string;
}

export const Checkbox: FC<Props> = ({
  name,
  defaultChecked,
  checked,
  onChange,
  label,
  ...other
}) => {
  let checkedProps;

  if (typeof checked !== 'undefined') {
    checkedProps = { checked };
  } else {
    checkedProps = { defaultChecked };
  }

  return (
    <label>
      <InlineFlex>
        <sc.Input
          {...other}
          {...checkedProps}
          type="checkbox"
          name={name}
          onChange={e => {
            onChange(e.currentTarget.checked);
          }}
        />
        <sc.CheckboxInput>
          <sc.CheckIcon
            Asset={SvgCheckmark}
            color="white"
            width="0.85em"
            height="0.85em"
          />
        </sc.CheckboxInput>
        {label && (
          <InlineFlex ml={2}>
            <Label htmlFor={name}>{label}</Label>
          </InlineFlex>
        )}
      </InlineFlex>
    </label>
  );
};
