import { useId, useRef } from 'react';
import { CloseIcon, UploadIcon } from '@/components/Icons';

interface FileUploadProps {
    label: string;
    hint?: string;
    accept?: string;
    required?: boolean;
    file: File | null;
    onChange: (file: File | null) => void;
    error?: string;
}

function formatBytes(bytes: number): string {
    if (bytes < 1024) {
        return `${bytes.toLocaleString('fa-IR')} بایت`;
    }

    const kb = bytes / 1024;
    if (kb < 1024) {
        return `${Math.round(kb).toLocaleString('fa-IR')} کیلوبایت`;
    }

    return `${(kb / 1024).toFixed(1).replace('.', '٫')} مگابایت`;
}

export default function FileUpload({
    label,
    hint,
    accept,
    required = false,
    file,
    onChange,
    error,
}: FileUploadProps) {
    const inputId = useId();
    const inputRef = useRef<HTMLInputElement>(null);

    function handleClear() {
        if (inputRef.current) {
            inputRef.current.value = '';
        }
        onChange(null);
    }

    return (
        <div>
            <label
                htmlFor={inputId}
                className="mb-1 block text-xs font-bold text-slate-700 sm:mb-1.5"
            >
                {label} {required && <span className="text-rose-600">*</span>}
            </label>

            <div className="relative flex flex-wrap items-center justify-between gap-2.5 rounded-xl border border-dashed border-slate-300 bg-slate-50/80 px-3 py-2.5 transition hover:border-brand-blue/60 hover:bg-blue-50/30">
                <input
                    ref={inputRef}
                    id={inputId}
                    type="file"
                    required={required && !file}
                    accept={accept}
                    onChange={(e) => onChange(e.target.files?.[0] ?? null)}
                    className="sr-only"
                />

                <div className="flex min-w-0 flex-1 items-center gap-2.5">
                    <label
                        htmlFor={inputId}
                        className="inline-flex shrink-0 cursor-pointer items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-bold text-brand-blue shadow-2xs transition hover:border-brand-blue hover:bg-blue-50"
                    >
                        <UploadIcon className="h-3.5 w-3.5" />
                        <span>{file ? 'تغییر فایل' : 'انتخاب فایل'}</span>
                    </label>

                    <div className="min-w-0 flex-1">
                        {file ? (
                            <div className="flex items-center gap-1.5 text-xs">
                                <span
                                    className="truncate font-semibold text-slate-800"
                                    dir="ltr"
                                >
                                    {file.name}
                                </span>
                                <span className="shrink-0 text-[11px] text-slate-500">
                                    ({formatBytes(file.size)})
                                </span>
                            </div>
                        ) : (
                            <span className="block truncate text-xs text-slate-500">
                                {hint || 'فایلی انتخاب نشده است'}
                            </span>
                        )}
                    </div>
                </div>

                {file && (
                    <button
                        type="button"
                        onClick={handleClear}
                        aria-label="حذف فایل انتخاب‌شده"
                        className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-slate-500 transition hover:bg-rose-50 hover:text-rose-600"
                    >
                        <CloseIcon className="h-4 w-4" />
                    </button>
                )}
            </div>

            {error && <p className="mt-1 text-xs text-rose-600">{error}</p>}
        </div>
    );
}
