import { Box, Stack, Typography } from "@mui/material";
import { useState } from "react";
import { useTranslation } from "react-i18next";

export const ImagePicker = ({ field, values, setFieldValue, isEdit }) => {
	const [fileName, setFileName] = useState("");
	const { t } = useTranslation();

	const handleFileChange = (event) => {
		const file = event.target.files[0];
		if (!file) {
			return;
		}

		setFileName(file.name);
		const reader = new FileReader();
		reader.onloadend = () => {
			setFieldValue(field.name, reader.result);
		};
		reader.readAsDataURL(file);
	};

	return (
		<Stack>
			<Typography variant="caption">{t("Select an image:")}</Typography>

			{isEdit && (
				<input
					type="file"
					accept="image/*"
					onChange={handleFileChange}
				/>
			)}

			{values[field.name] && (
				<Stack>
					<Typography variant="caption">{t("Preview:")}</Typography>
					<Box
						sx={{
							maxWidth: "20rem",
							maxHeight: "20rem",
						}}
					>
						<img
							src={values[field.name]}
							alt={fileName}
							className="w-100 h-100"
						/>
					</Box>
				</Stack>
			)}
		</Stack>
	);
};
