import { ActionIcon, Avatar, Box, Indicator, LoadingOverlay } from '@mantine/core';
import { generateImageUrl, randomDelay } from '../../ultils';
import { useEffect, useState, useCallback, useRef } from 'react';
import classNames from 'classnames';
import { useImagesDetected } from '../../stores/use-images-detected';
import { IconTrash } from '@tabler/icons-react';

export const ImageDetect = ({ file, onClick, currentData, onDelete, onDetected }) => {
	const [loading, setLoading] = useState(false);
	const [data, setData] = useState();
	const [isVisible, setIsVisible] = useState(false);
	const ref = useRef(null);
	const [isDetected, setIsDetected] = useState(false);

	useEffect(() => {
		if (!file?.points) return;

		setData(file);
	}, [file]);

	// useEffect(() => {
	// 	if (isVisible || currentData?.image_name !== file?.image_name) return;

	// 	ref.current?.scrollIntoView({
	// 		behavior: 'smooth',
	// 		block: 'center',
	// 		inline: 'nearest',
	// 	});
	// }, [currentData, isVisible]);

	useEffect(() => {
		const observer = new IntersectionObserver(
			([entry]) => {
				setIsVisible(entry.isIntersecting);
			},
			{ threshold: 1 },
		);

		if (ref.current) observer.observe(ref.current);

		return () => {
			if (ref.current) observer.unobserve(ref.current);
		};
	}, []);

	return (
		<Box
			display={isDetected ? 'none' : 'flex'}
			ref={ref}
			onClick={data?.points && onClick ? () => onClick(data) : undefined}
			className={classNames('flex items-center justify-between gap-3 rounded-md p-3 max-w-full relative', {
				['hover:bg-gray-900 cursor-pointer']: !loading,
				['cursor-not-allowed']: loading,
				['bg-gray-900']: currentData?.image_name === data?.image_name,
			})}>
			<Box className="flex items-center gap-3 w-full flex-1 max-w-full">
				<Indicator color="red" disabled={!!data?.isSave}>
					<Avatar size={'md'} src={generateImageUrl(data?.image_path)} radius="sm" />
				</Indicator>
				<span className="truncate flex-1 w-[140px]">{data?.image_name || ''}</span>
			</Box>
			<ActionIcon
				color="red"
				onClick={
					onDelete
						? (e) => {
								e.stopPropagation();
								onDelete(data);
						  }
						: undefined
				}>
				<IconTrash size={14} />
			</ActionIcon>

			<LoadingOverlay
				visible={loading}
				zIndex={10}
				overlayProps={{ radius: 'sm', blur: 2 }}
				loaderProps={{
					size: 'xs',
				}}
			/>
		</Box>
	);
};
