import { CloudUploadOutlined } from "@mui/icons-material";
import { Box, Button, Stack, styled, Typography } from "@mui/material";
import { useTranslation } from "react-i18next";

import { Entity } from "../../../models/Entity";
import { CardField } from "../CardField";

interface Props<T extends Entity> {
	field: CardField<T>;
	values: T;
	setFieldValue: (name: keyof T, values: unknown) => void;
	isEdit: boolean;
}

const VisuallyHiddenInput = styled("input")({
	clip: "rect(0 0 0 0)",
	clipPath: "inset(50%)",
	height: 1,
	overflow: "hidden",
	position: "absolute",
	bottom: 0,
	left: 0,
	whiteSpace: "nowrap",
	width: 1,
});

export function ImagePickerCardField<T extends Entity>({
	field,
	values,
	setFieldValue,
	isEdit,
}: Props<T>) {
	const { t } = useTranslation();

	const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
		if (!event.target.files || !event.target.files[0]) {
			return;
		}

		const file = event.target.files[0];

		const reader = new FileReader();
		reader.onloadend = () => {
			if (!reader.result) {
				return;
			}

			setFieldValue(field.name, reader.result);
		};
		reader.readAsDataURL(file);
	};

	return (
		<Stack spacing={1} key={field.name.toString()}>
			<Typography variant="caption">{t("Select an image:")}</Typography>

			{isEdit && (
				<Button
					component="label"
					role={undefined}
					variant="contained"
					tabIndex={-1}
					startIcon={<CloudUploadOutlined />}
				>
					{t("Upload file")}
					<VisuallyHiddenInput
						type="file"
						accept="image/*"
						onChange={handleFileChange}
						multiple
					/>
				</Button>
			)}

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