import React from "react";
import Typography, { ITypo, ITypoColor } from "@Front/Components/DesignSystem/Typography";
import { ReactNode } from "react";
import CopyIcon from "@Assets/Icons/copy.svg";
import BaseField, { IProps as IBaseFieldProps } from "../BaseField";
import classes from "./classes.module.scss";
import classnames from "classnames";
import Image from "next/image";

export type IProps = IBaseFieldProps & {
	canCopy?: boolean;
	password?: boolean;
};

export default class TextField extends BaseField<IProps> {
	constructor(props: IProps) {
		super(props);
		this.state = this.getDefaultState();
	}

	public override render(): ReactNode {
		const value = this.state.value ?? "";
		return (
			<Typography typo={ITypo.TEXT_MD_REGULAR} color={ITypoColor.COLOR_NEUTRAL_500}>
				<div className={classes["root"]} data-is-errored={this.hasError().toString()}>
					<input
						onChange={this.onChange}
						data-value={value}
						data-has-validation-errors={(this.state.validationError === null).toString()}
						className={classnames(classes["input"], this.props.className)}
						value={value}
						onFocus={this.onFocus}
						onBlur={this.onBlur}
						name={this.props.name}
						disabled={this.props.disabled}
						type={this.props.password ? "password" : "text"}
					/>
					<div className={classes["fake-placeholder"]}>
						{this.props.placeholder} {!this.props.required && " (Facultatif)"}
					</div>
					{this.props.canCopy && (
						<div className={classes["copy-icon"]} onClick={this.onCopyClick}>
							<Image src={CopyIcon} alt="Copy icon" />
						</div>
					)}
				</div>
				{this.hasError() && <div className={classes["errors-container"]}>{this.renderErrors()}</div>}
			</Typography>
		);
	}

	private onCopyClick = (): void => {
		if (this.props.canCopy) {
			navigator.clipboard.writeText(this.state.value ?? "");
		}
	};
}
