import { forwardRef } from 'react';
import { Group, Text } from '@mantine/core';
import { Dropzone as Dz, IMAGE_MIME_TYPE } from '@mantine/dropzone';
import { IconPhoto, IconUpload, IconX } from '@tabler/icons-react';

export const Dropzone = forwardRef(({ onErorrFiles, onFilesChange, onReject, hidden, openRef }, ref) => {
	const handleDrop = async (files) => {
		const checkImageSize = (file) => {
			return new Promise((resolve, reject) => {
				const img = new Image();
				const objectUrl = URL.createObjectURL(file);

				img.src = objectUrl;

				img.onload = () => {
					if (img.width >= 500 && img.height >= 500) {
						resolve(file);
					} else {
						reject(`${file.name} is too small (${img.width}x${img.height})`);
					}
					URL.revokeObjectURL(objectUrl);
				};

				img.onerror = () => {
					reject(`${file.name} is not a valid image.`);
					URL.revokeObjectURL(objectUrl);
				};
			});
		};

		try {
			const results = await Promise.allSettled(files.map(checkImageSize));

			const acceptedFiles = results.filter((res) => res.status === 'fulfilled').map((res) => res.value);
			const errors = results.filter((res) => res.status === 'rejected').map((res) => `❌ ${res.reason}`);

			if (errors.length > 0 && onErorrFiles) {
				onErorrFiles(errors);
			}

			if (onFilesChange) {
				onFilesChange(acceptedFiles, files);
			}
		} catch (err) {
			console.error('Unexpected error:', err);
		}
	};

	return (
		<Dz
			display={!hidden ? 'none' : 'flex'}
			openRef={openRef}
			ref={ref}
			style={{ width: '100%', height: '400px', display: 'flex', justifyContent: 'center' }}
			onDrop={handleDrop}
			onReject={onReject}
			accept={IMAGE_MIME_TYPE}>
			<Group justify="center" gap="xl" mih={220} h={'100%'} style={{ pointerEvents: 'none' }}>
				<Dz.Accept>
					<IconUpload size={52} color="var(--mantine-color-blue-6)" stroke={1.5} />
				</Dz.Accept>
				<Dz.Reject>
					<IconX size={52} color="var(--mantine-color-red-6)" stroke={1.5} />
				</Dz.Reject>
				<Dz.Idle>
					<IconPhoto size={52} color="var(--mantine-color-dimmed)" stroke={1.5} />
				</Dz.Idle>

				<div>
					<Text size="xl" inline>
						Drag images here or click to select files
					</Text>
					<Text size="sm" c="dimmed" inline mt={7}>
						Attach as many files as you like, each file should not exceed 5mb
					</Text>
				</div>
			</Group>
		</Dz>
	);
});
