"use client";

import type { VariantProps } from "class-variance-authority";
import { ImageIcon } from "lucide-react";
import type React from "react";
import { useRef } from "react";
import { Button, type buttonVariants } from "@/components/ui/button";

interface ImagePickerProps extends VariantProps<typeof buttonVariants> {
	onFileSelect?: (file: File) => void;
	className?: string;
	children?: React.ReactNode;
	disabled?: boolean;
}

export function ImagePicker({
	onFileSelect,
	className,
	children,
	variant = "ghost",
	size = "icon",
	disabled = false,
}: ImagePickerProps) {
	const fileInputRef = useRef<HTMLInputElement>(null);

	const handleButtonClick = () => {
		fileInputRef.current?.click();
	};

	const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
		const file = event.target.files?.[0];
		if (file && onFileSelect) {
			onFileSelect(file);
		}
		if (fileInputRef.current) {
			fileInputRef.current.value = "";
		}
	};

	return (
		<>
			<input
				ref={fileInputRef}
				type="file"
				accept="image/png,image/jpeg,image/webp"
				onChange={handleFileChange}
				className="hidden"
			/>
			<Button
				onClick={handleButtonClick}
				variant={variant}
				size={size}
				className={className}
				disabled={disabled}
				aria-label="Attach image"
			>
				{children || <ImageIcon className="h-4 w-4" />}
			</Button>
		</>
	);
}
