import { useState, useRef, useEffect, ImgHTMLAttributes } from 'react';

interface LazyImageProps extends ImgHTMLAttributes<HTMLImageElement> {
    src: string;
    alt: string;
    placeholder?: string;
    fallback?: string;
    blur?: boolean;
}

export function LazyImage({
    src,
    alt,
    placeholder = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"%3E%3Crect fill="%23e2e8f0" width="100" height="100"/%3E%3C/svg%3E',
    fallback = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"%3E%3Crect fill="%23f1f5f9" width="100" height="100"/%3E%3Ctext x="50" y="50" text-anchor="middle" dy=".3em" fill="%2394a3b8" font-size="10"%3ENo Image%3C/text%3E%3C/svg%3E',
    blur = true,
    className = '',
    ...props
}: LazyImageProps) {
    const [isLoaded, setIsLoaded] = useState(false);
    const [isInView, setIsInView] = useState(false);
    const [hasError, setHasError] = useState(false);
    const imgRef = useRef<HTMLImageElement>(null);

    useEffect(() => {
        if (!imgRef.current) return;

        const observer = new IntersectionObserver(
            ([entry]) => {
                if (entry.isIntersecting) {
                    setIsInView(true);
                    observer.disconnect();
                }
            },
            {
                rootMargin: '50px', // Load 50px before entering viewport
                threshold: 0.01
            }
        );

        observer.observe(imgRef.current);
        return () => observer.disconnect();
    }, []);

    const handleLoad = () => {
        setIsLoaded(true);
    };

    const handleError = () => {
        setHasError(true);
    };

    return (
        <div className={`relative overflow-hidden ${className}`} {...props}>
            {/* Placeholder */}
            {!isLoaded && (
                <img
                    src={placeholder}
                    alt=""
                    className={`absolute inset-0 w-full h-full object-cover ${blur ? 'blur-sm scale-105' : ''} transition-opacity duration-300`}
                    style={{ opacity: isLoaded ? 0 : 1 }}
                />
            )}

            {/* Actual image */}
            <img
                ref={imgRef}
                src={isInView ? (hasError ? fallback : src) : placeholder}
                alt={alt}
                onLoad={handleLoad}
                onError={handleError}
                className={`w-full h-full object-cover transition-opacity duration-500 ${isLoaded ? 'opacity-100' : 'opacity-0'}`}
            />

            {/* Loading shimmer */}
            {!isLoaded && isInView && !hasError && (
                <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent animate-shimmer" />
            )}
        </div>
    );
}

// Hook for lazy loading any element
export function useLazyLoad<T extends HTMLElement>(options?: IntersectionObserverInit) {
    const ref = useRef<T>(null);
    const [isInView, setIsInView] = useState(false);

    useEffect(() => {
        if (!ref.current) return;

        const observer = new IntersectionObserver(
            ([entry]) => {
                if (entry.isIntersecting) {
                    setIsInView(true);
                    observer.disconnect();
                }
            },
            {
                rootMargin: '100px',
                threshold: 0,
                ...options
            }
        );

        observer.observe(ref.current);
        return () => observer.disconnect();
    }, []);

    return { ref, isInView };
}
