import { CancelOutlined, SearchOutlined } from "@mui/icons-material";
import { Box, IconButton, TextField } from "@mui/material";
import { useFormik } from "formik";
import { FC } from "react";
import { useTranslation } from "react-i18next";

interface Props {
	onSearch: (searchTerm: string) => void;
	labelKey: string;
	search: string;
}

export const SearchBox: FC<Props> = (props) => {
	const { t } = useTranslation();

	const {
		handleSubmit,
		values,
		handleBlur,
		handleChange,
		resetForm,
		submitForm,
	} = useFormik({
		initialValues: {
			searchTerm: props.search,
		},
		onSubmit: (values) => {
			props.onSearch(values.searchTerm);
		},
	});

	const handleClearSearchTerm = () => {
		props.onSearch("");
		resetForm({
			values: {
				searchTerm: "",
			},
		});
		submitForm();
	};

	return (
		<form onSubmit={handleSubmit}>
			<Box
				sx={{
					display: "flex",
					alignItems: "center",
				}}
			>
				<TextField
					label={t(props.labelKey)}
					variant="outlined"
					sx={{
						flexGrow: 1,
						padding: 0,
					}}
					name="searchTerm"
					value={values.searchTerm}
					onBlur={handleBlur}
					onChange={handleChange}
					size="small"
					slotProps={{
						input: {
							endAdornment: (
								<>
									<IconButton
										type="button"
										onClick={handleClearSearchTerm}
									>
										<CancelOutlined fontSize="inherit" />
									</IconButton>
									<IconButton type="submit">
										<SearchOutlined fontSize="inherit" />
									</IconButton>
								</>
							),
						},
					}}
				/>
			</Box>
		</form>
	);
};
