import { useEffect, useRef, useState } from 'react';
import InputError from '@/components/input-error';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

type LogoUploaderProps = {
    name?: string;
    label?: string;
    currentUrl?: string | null;
    error?: string;
    /** Ref pour récupérer l'input file (ex. pour envoi formulaire). */
    inputRef?: React.RefObject<HTMLInputElement | null>;
    /** Callback quand le fichier change. */
    onFileChange?: (file: File | null) => void;
};

export default function LogoUploader({
    name = 'logo',
    label = 'Logo',
    currentUrl,
    error,
    inputRef: inputRefProp,
    onFileChange,
}: LogoUploaderProps) {
    const inputRefInternal = useRef<HTMLInputElement>(null);
    const inputRef = inputRefProp ?? inputRefInternal;
    const [previewUrl, setPreviewUrl] = useState<string | null>(
        currentUrl ?? null,
    );

    useEffect(() => {
        setPreviewUrl(currentUrl ?? null);
    }, [currentUrl]);

    useEffect(() => {
        return () => {
            if (previewUrl && previewUrl !== currentUrl && previewUrl.startsWith('blob:')) {
                URL.revokeObjectURL(previewUrl);
            }
        };
    }, [previewUrl, currentUrl]);

    const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        if (!file) {
            onFileChange?.(null);
            setPreviewUrl(currentUrl ?? null);
            return;
        }
        if (previewUrl && previewUrl.startsWith('blob:')) {
            URL.revokeObjectURL(previewUrl);
        }
        setPreviewUrl(URL.createObjectURL(file));
        onFileChange?.(file);
    };

    return (
        <div className="space-y-2">
            <Label>{label}</Label>
            <div className="flex flex-wrap items-center gap-4">
                {previewUrl ? (
                    <img
                        src={previewUrl}
                        alt="Aperçu du logo"
                        className="h-20 w-20 rounded-lg border object-cover"
                    />
                ) : (
                    <div className="flex h-20 w-20 items-center justify-center rounded-lg border border-dashed text-xs text-muted-foreground">
                        Aucun logo
                    </div>
                )}
                <div className="flex flex-col gap-2">
                    <Input
                        ref={inputRef}
                        type="file"
                        name={name}
                        accept="image/*"
                        onChange={handleFileChange}
                    />
                    <span className="text-xs text-muted-foreground">
                        Formats recommandés: JPG/PNG, carré.
                    </span>
                </div>
            </div>
            <InputError message={error} />
        </div>
    );
}
