import React from "react";

import Tooltip from "../ToolTip";
import Typography, { ETypo, ETypoColor } from "../Typography";
import classes from "./classes.module.scss";
import classNames from "classnames";
import { IOption } from "../Form/SelectFieldOld";

type IProps = {
	name?: string;
	option: IOption;
	toolTip?: string;
	onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
	checked: boolean;
	disabled?: boolean;
};

type IState = {
	checked: boolean;
};

export default class CheckBox extends React.Component<IProps, IState> {
	static defaultProps = {
		toolTip: "",
		checked: false,
		disabled: false,
	};

	constructor(props: IProps) {
		super(props);
		this.state = {
			checked: this.props.checked ?? false,
		};

		this.onChange = this.onChange.bind(this);
	}

	public override render(): JSX.Element {
		return (
			<Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.COLOR_ERROR_600}>
				<label className={classNames(classes["root"], this.props.disabled && classes["disabled"])}>
					<input
						type="checkbox"
						name={this.props.name ?? (this.props.option.value as string)}
						value={this.props.option.value as string}
						onChange={this.onChange}
						checked={this.state.checked}
					/>
					<div className={classes["content"]}>
						{this.props.option.label && (
							<Typography className={classes["label"]} typo={ETypo.TEXT_MD_REGULAR}>
								{this.props.option.label}
							</Typography>
						)}
						{this.props.option.description && (
							<Typography className={classes["description"]} typo={ETypo.TEXT_MD_LIGHT}>
								{this.props.option.description}
							</Typography>
						)}
					</div>

					{this.props.toolTip && <Tooltip className={classes["tooltip"]} text={this.props.toolTip} />}
				</label>
			</Typography>
		);
	}

	public override componentDidUpdate(prevProps: Readonly<IProps>): void {
		if (prevProps.checked !== this.props.checked) {
			this.setState({
				checked: this.props.checked,
			});
		}
	}

	private onChange(e: React.ChangeEvent<HTMLInputElement>) {
		this.setState({
			checked: !this.state.checked,
		});

		this.props.onChange && this.props.onChange(e);
	}
}
