import { CircularProgress, MenuItem, TextField } from "@mui/material";
import { ReactNode, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { ZERO_ID } from "../../../../constants";
import { KeyValue } from "../../../../models/KeyValue";
import { Entity } from "../../../models/Entity";
import { FieldProps } from "../../../models/FieldProps";
import { SelectFieldProps } from "../../../models/SelectFieldProps";

export function TextCardField<T extends Entity>(props: SelectFieldProps<T>) {
	const [options, setOptions] = useState<KeyValue[]>([]);
	const [isLoading, setIsLoading] = useState(false);
	const values = props.formik.values;
	const loadOptions = props.loadOptions;
	const { t } = useTranslation();

	useEffect(() => {
		if (loadOptions) {
			setIsLoading(true);
			loadOptions(values)
				.then((options) => {
					setOptions(options);
				})
				.finally(() => {
					setIsLoading(false);
				});
		}
	}, [values, loadOptions]);

	useEffect(() => {
		if (props.options) {
			setOptions(props.options);
		}
	}, [props.options]);

	const getHelperText = (field: FieldProps<T>): ReactNode => {
		if (
			!props.formik.touched[field.name] ||
			!props.formik.errors[field.name]
		) {
			return null;
		}

		return props.formik.errors[field.name]?.toString();
	};

	if (isLoading) {
		return <CircularProgress />;
	}

	return (
		<TextField
			{...props}
			key={props.name.toString()}
			disabled={props.formik.isSubmitting}
			slotProps={{
				input: {
					readOnly: props.readOnly,
				},
			}}
			select={props.type === "select"}
			name={props.name.toString()}
			label={t(props.title)}
			title={t(props.title)}
			value={values[props.name] ?? ""}
			error={
				props.formik.touched[props.name] &&
				Boolean(props.formik.errors[props.name])
			}
			helperText={getHelperText(props)}
			multiline={props.type === "multiline"}
			fullWidth
			onChange={props.formik.handleChange}
			onBlur={props.formik.handleBlur}
		>
			<MenuItem value={ZERO_ID}>---</MenuItem>
			{options &&
				options.map((option) => (
					<MenuItem key={option.key} value={option.key}>
						{option.value}
					</MenuItem>
				))}
		</TextField>
	);
}
