import cx from "classnames";
import React from "react";

const CLASS_ROOT = "checkbox";

export type CheckboxSize = "default" | "large";

export interface CheckboxProps
  extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "size"> {
  /** Html id attribute */
  id: string;
  /** Checked state. */
  isChecked?: boolean;
  /** Disabled state. */
  isDisabled?: boolean;
  /** Invalid state */
  isInvalid?: boolean;
  /** Checkbox is displayed as Toggle */
  isToggle?: boolean;
  /** Html name attribute. Id is used when not set.*/
  name?: string;
  /** Size of element. */
  size?: CheckboxSize;
  className?: string;
}

const defaultProps = {
  size: "default" as CheckboxSize,
};

const Checkbox: React.FC<CheckboxProps> = ({
  id,
  isChecked,
  isDisabled,
  isInvalid,
  isToggle,
  name,
  size = defaultProps.size,
  className,
  ...other
}) => {
  const classes = cx(CLASS_ROOT, className, {
    [`${CLASS_ROOT}--${size}`]: size !== defaultProps.size,
    "is-invalid": isInvalid,
  });

  const inputName = name || id;

  const CheckboxInput = () => (
    <>
      <input
        className={classes}
        type="checkbox"
        id={id}
        name={inputName}
        defaultChecked={isChecked}
        disabled={isDisabled}
        {...other}
      />
      <div className={`${CLASS_ROOT}-display`} />
    </>
  );

  return isToggle ? (
    <div className={isToggle ? "checkbox--toggle" : ""}>
      <CheckboxInput />
    </div>
  ) : (
    <CheckboxInput />
  );
};

Checkbox.displayName = "Checkbox";

export { Checkbox };
