'use client';

import { useCallback, useState } from 'react';
import Image from 'next/image';
import { Controller, useFormContext } from 'react-hook-form';
import { useDropzone } from 'react-dropzone';
import { UploadIcon, X, RotateCcw } from 'lucide-react';

interface RHFAvatarImageProps {
	name: string;
	label?: string;
	size?: number;
}

const RHFAvatarImage = ({
	name,
	label = 'Profile Picture',
	size = 138,
}: RHFAvatarImageProps) => {
	const { control, setValue } = useFormContext();
	const [lastFile, setLastFile] = useState<File | null>(null);

	/** DROP INPUT: only store file — do NOT upload */
	const onDrop = useCallback((acceptedFiles: File[]) => {
		if (!acceptedFiles?.length) return;
		const file = acceptedFiles[0];
		setLastFile(file);
		setValue(name, file); // hold file
	}, []);

	const dropzone = useDropzone({
		onDrop,
		multiple: false,
		accept: { 'image/*': ['.png', '.jpg', '.jpeg'] },
	});

	/** REMOVE ONLY CLEARS THE FIELD */
	const handleRemove = () => {
		setLastFile(null);
		setValue(name, null);
	};

	/** RELOAD VALUE FROM LAST FILE */
	const handleRetry = () => {
		if (lastFile) {
			setValue(name, lastFile);
		}
	};

	return (
		<Controller
			name={name}
			control={control}
			render={({ field, fieldState }) => {
				const value = field.value as File | string | null;

				const isFile = value instanceof File;
				const isUrl = typeof value === 'string';

				const preview = (() => {
					if (isFile) return URL.createObjectURL(value);
					if (isUrl) return value;
					return null;
				})();

				return (
					<div className="flex flex-col items-center gap-3 relative">
						{/* Upload Surface */}
						<div
							{...dropzone.getRootProps()}
							className="cursor-pointer relative rounded-full overflow-hidden border-[5px] border-[#8CC63F4D] bg-[#D9D9D9]"
							style={{ width: size, height: size }}
						>
							<input {...dropzone.getInputProps()} />

							{/* PREVIEW */}
							{preview ? (
								<Image
									src={preview}
									width={size}
									height={size}
									alt="avatar"
									className="object-cover w-full h-full"
								/>
							) : (
								<div className="w-full h-full flex items-center justify-center">
									<UploadIcon
										size={size * 0.4}
										className="text-gray-500"
									/>
								</div>
							)}
						</div>
						{/* DELETE BUTTON */}
						{value && (
							<button
								onClick={(e) => {
									e.preventDefault();
									handleRemove();
								}}
								className="absolute top-3 right-4 bg-red-500 text-white rounded-full p-1"
							>
								<X size={14} />
							</button>
						)}

						{/* INFO AREA */}
						<div className="flex flex-col text-center text-sm">
							<p className="font-semibold">{label}</p>

							{fieldState.error && (
								<p className="text-red-500">
									{fieldState.error.message}
								</p>
							)}
						</div>

						{/* RETRY IF LAST FILE EXISTS */}
						{lastFile && !value && (
							<button
								onClick={handleRetry}
								type="button"
								className="flex items-center gap-1 text-orange-600 text-sm"
							>
								Retry <RotateCcw size={14} />
							</button>
						)}
					</div>
				);
			}}
		/>
	);
};

export default RHFAvatarImage;
