import LoopIcon from "@Assets/Icons/loop.svg";
import Image from "next/image";
import React from "react";

import Typography, { ITypo } from "../Typography";
import classes from "./classes.module.scss";

type IProps = {
	onChange?: (input: string) => void;
	placeholder?: string;
};

type IState = {
	hasValue: boolean;
};

export default class SearchBar extends React.Component<IProps, IState> {
	static defaultProps = {
		placeholder: "Search",
	};

	public constructor(props: IProps) {
		super(props);
		this.state = {
			hasValue: false,
		};
		this.doesInputHaveValue = this.doesInputHaveValue.bind(this);
		this.onChange = this.onChange.bind(this);
	}
	public override render(): JSX.Element {
		return (
			<div className={classes["root"]}>
				<Image src={LoopIcon} alt="Loop icon" />
				{!this.state.hasValue && (
					<Typography typo={ITypo.P_ERR_18}>
						<div className={classes["fake-placeholder"]}>{this.props.placeholder}</div>
					</Typography>
				)}
				<input type="text" placeholder="" className={classes["input"]} onChange={this.onChange} />
			</div>
		);
	}

	private onChange(event: React.ChangeEvent<HTMLInputElement>) {
		const hasValue = event.target.value.length > 0;
		this.doesInputHaveValue(hasValue);
		if (!this.props.onChange) return;
		this.props.onChange(event.target.value);
	}

	private doesInputHaveValue(hasValue: boolean) {
		this.setState({ hasValue });
	}
}
