import React from "react";
import { ReactNode } from "react";

import { IOption } from "../../Dropdown/DropdownMenu/DropdownOption";
import BaseField, { IProps as IBaseFieldProps, IState as IBaseFieldState } from "../BaseField";
import classes from "./classes.module.scss";
import Dropdown from "../../Dropdown";

export type IProps = IBaseFieldProps & {
	onSelectionChange?: (option: IOption) => void;
	options: IOption[];
	selectedOption?: IOption | null;
	label?: string;
};

type IState = IBaseFieldState & {
	selectedOption: IOption | null;
};

export default class SelectField extends BaseField<IProps, IState> {
	constructor(props: IProps) {
		super(props);
		this.state = {
			selectedOption: this.props.selectedOption ?? null,
			...this.getDefaultState(),
		};

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

	private handleOnChange = (option: IOption) => {
		this.setState({ selectedOption: option });
		this.props.onSelectionChange?.(option);
	};

	public override componentDidUpdate(prevProps: IProps): void {
		if (prevProps.selectedOption !== this.props.selectedOption) {
			this.setState({ selectedOption: this.props.selectedOption ?? null });
		}
	}

	public override render(): ReactNode {
		return (
			<div className={classes["root"]}>
				<Dropdown
					options={this.props.options}
					placeholder={this.props.placeholder}
					onSelectionChange={this.handleOnChange}
					selectedOption={this.state.selectedOption}
					label={this.props.label}
					disabled={this.props.disabled}
				/>
				{this.state.selectedOption && (
					<input
						className={classes["hidden-input"]}
						name={this.props.name}
						type="text"
						defaultValue={this.state.selectedOption.id}
						hidden
					/>
				)}
				{this.hasError() && <div className={classes["errors-container"]}>{this.renderErrors()}</div>}
			</div>
		);
	}
}
