import * as React from 'react';
import { useState, useEffect } from 'react';
import classnames from 'classnames';
import IReactComponentProps from '../../../common/structures/IReactComponentProps';
import styles from './Checkbox.scss';
import CheckmarkSVG from '../../../svg/checkmark--sm.svg';
import CheckMixedSVG from '../../../svg/checkmark--mixed.svg';
import { FunctionGeneric } from '../../../common/structures/Generics';

interface IProps extends IReactComponentProps {
	checked?: boolean | 'mixed';
	disabled?: boolean;
	label?: string;
	name?: string;
	onChange?: FunctionGeneric;
}

const Checkbox: React.FC<IProps> = ({
	checked = false,
	disabled = false,
	label,
	name,
	onChange,
	className,
	id,
	style,
}) => {
	const [isChecked, setIsChecked] = useState<boolean | 'mixed'>(checked);

	useEffect(() => {
		setIsChecked(checked);
	}, [checked]);

	const handleChange = () => {
		const newChecked: boolean = isChecked === 'mixed' ? true : !isChecked;

		setIsChecked(newChecked);

		if (onChange) {
			onChange(newChecked);
		}
	};

	return (
		<div
			className={classnames(
				styles.Checkbox,
				{
					[styles.Checkbox__Checked]: isChecked === true,
					[styles.Checkbox__CheckMixed]: isChecked === 'mixed',
					[styles.Checkbox__Disabled]: disabled,
				},
				className
			)}
			id={id}
			style={style}
		>
			<label className={styles.Checkbox_Label}>
				<input
					type="checkbox"
					className={styles.Checkbox_InputHidden}
					checked={isChecked === true}
					disabled={disabled}
					name={name}
					onChange={handleChange}
				/>
				<span className={styles.Checkbox_CheckmarkContainer}>
					{isChecked === true && <CheckmarkSVG aria-hidden className={styles.Checkbox_Checkmark} />}
					{isChecked === 'mixed' && <CheckMixedSVG aria-hidden className={styles.Checkbox_CheckmarkMixed} />}
				</span>
				{label && <span className={styles.Checkbox_LabelContents}>{label}</span>}
			</label>
		</div>
	);
};

export default Checkbox;
