import React, { useEffect, useRef, useState, forwardRef, useImperativeHandle, memo } from "react";
import { Box, LoadingOverlay } from "@mantine/core";
import PointsBlur from "./PointsBlur";
import { generateImageUrl } from "../../ultils";

const ImageLabel = forwardRef(({ data }, ref) => {
	const [imageSrc, setImageSrc] = useState(null);
	const blurredRegions = useRef([]);
	const [loaded, setLoaded] = useState(false);
	const [reloading, setReloading] = useState(false);
	const [listLabel, setListLabel] = useState([]);
	const [infoImage, setInfoImage] = useState({});
	const [imageName, setImageName] = useState("");

	// Expose blurredRegions cho component cha
	useImperativeHandle(ref, () => ({
		getBlurredRegions: () => blurredRegions.current,
		setBlurredRegions: (regions) => {
			blurredRegions.current = regions;
		},
		getSaveData: () => {
			return {
				blurredRegions: blurredRegions.current,
				imageName,
				infoImage,
				listLabel,
			};
		},
	}));

	useEffect(() => {
		if (data?.error) {
			alert(data.error);
		} else {
			if (data?.points) {
				blurredRegions.current = data?.points?.map((pre) => {
					const arrLabel = pre?.label?.split(".");
					const label = arrLabel?.length > 1 ? arrLabel[1] : arrLabel[0];
					const subLabel = arrLabel?.length > 1 ? arrLabel[0] : null;
					return [
						{ x: pre.x1, y: pre.y1, label: label, subLabel: subLabel },
						{ x: pre.x2, y: pre.y1, label: label, subLabel: subLabel },
						{ x: pre.x2, y: pre.y2, label: label, subLabel: subLabel },
						{ x: pre.x1, y: pre.y2, label: label, subLabel: subLabel },
					];
				});
			}
			setListLabel(
				Object.entries(data?.labels).map(([id, name]) => ({
					id: Number(id),
					name,
				}))
			);
			setImageSrc(generateImageUrl(data?.image_path));
			setImageName(data?.image_name);
			setTimeout(() => setReloading((pre) => !pre), 1000);
		}
	}, [data]);

	return (
		<Box className="w-full h-full flex items-center justify-center relative">
			<PointsBlur
				imageSrc={imageSrc}
				blurredRegions={blurredRegions}
				loaded={loaded}
				setLoaded={setLoaded}
				reloading={reloading}
				setReloading={setReloading}
				setInfoImage={setInfoImage}
				listLabel={listLabel}
			/>
		</Box>
	);
});

export default memo(ImageLabel);
