import { type SxProps, TextField, type Theme } from "@mui/material";
import { getLocalizedString } from "@olenbetong/appframe-core";
import { useEffect, useState } from "react";

type ElementNumberTextFieldProps = {
	value?: string | null;
	defaultValue?: string | null;
	onChange?: (value: string) => void;
	disabled?: boolean;
	sx?: SxProps<Theme>;
};

export function ElementNumberTextField({ value, defaultValue, onChange, disabled, sx }: ElementNumberTextFieldProps) {
	let [elementNumber, setElementNumber] = useState<string>(defaultValue ?? "");
	let elementNumberValue = value === undefined ? elementNumber : value;

	useEffect(() => {
		if (value === undefined && defaultValue) {
			setElementNumber(defaultValue);
		}
	}, [defaultValue, value]);

	function handleChange(value: string) {
		onChange?.(value);
		setElementNumber(value);
	}

	return (
		<TextField
			name="ElementNumber"
			id="NewElementDamage_ElementNr"
			value={elementNumberValue}
			onChange={(event) => handleChange(event.currentTarget.value)}
			label={getLocalizedString("Element number")}
			fullWidth
			autoComplete="off"
			disabled={disabled ?? false}
			sx={{ ...sx }}
		/>
	);
}
