import { SecondaryButton } from "$/component/button";
import type { FileInputProps } from "$/types/Input";
import { humanReadableBytes } from "$/util/FileUtil";
import clsx from "clsx";
import { useRef, useState } from "react";


export default function FileInput({
	id,
	className,
	name,
	minSize,
	maxSize,
	showFileName,
	showSize,
	onChange,
	disabled,
	children
}: FileInputProps){
	const inputRef = useRef<HTMLInputElement>(null);
	const [ file, setFile ] = useState<File>();


	return (
		<div
			className="flex flex-row items-center justify-between w-full border-2 rounded-lg"
		>
			<input
				ref={inputRef}
				id={id}
				type="file"
				className={clsx(
					"sr-only",
					className
				)}
				name={name}
				onChange={(e) => { setFile(e.target.files?.[0]); onChange?.(e.target.files?.[0]); }}
				disabled={disabled}
			/>
			<div
				className="flex flex-row items-center justify-between grow w-full px-2"
			>
				{
					children && !showFileName &&
					<div>{children}</div>
				}
				{
					showFileName &&
					<div>{file?.name}</div>
				}
				{
					!children && !showFileName &&
					<>&nbsp;</>
				}
				{
					showSize &&
					<div
						className={clsx(
							{
								"text-red-600": minSize && file?.size && file?.size < minSize,
								"text-red-600 ": maxSize && file?.size && file?.size > maxSize,
								"text-green-600": minSize && !maxSize && file?.size && file?.size > minSize,
								"text-green-600 ": !minSize && maxSize && file?.size && file?.size < maxSize,
								" text-green-600": minSize && maxSize && file?.size && file?.size > minSize && file?.size < maxSize
							}
						)}
					>
						{humanReadableBytes(file?.size ?? 0)}
					</div>
				}
			</div>
			<div
				className="border-l-2"
			>
				<SecondaryButton
					className="text-nowrap rounded-r-lg"
					rounding="none"
					onClick={() => { inputRef.current?.click(); }}
				>
					Click Me
				</SecondaryButton>
			</div>
		</div>
	);
}
