import React, { useState, useRef, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';

/**
 * BlurImage - Progressive image loading with blur-up effect
 * @param {Object} props
 * @param {string} props.src - Image source URL
 * @param {string} [props.alt] - Alt text
 * @param {string} [props.className] - Additional CSS classes
 * @param {string} [props.placeholderColor] - Background color while loading
 * @param {Function} [props.onLoad] - Callback when image loads
 * @param {Function} [props.onError] - Callback when image fails
 * @param {React.ReactNode} [props.fallback] - Fallback content on error
 * @param {boolean} [props.zoom] - Enable zoom on hover
 */
export function BlurImage({
  src,
  alt = '',
  className = '',
  placeholderColor = 'rgba(30, 40, 60, 0.8)',
  onLoad,
  onError,
  fallback,
  zoom = true,
}) {
  const [isLoaded, setIsLoaded] = useState(false);
  const [hasError, setHasError] = useState(false);
  const [isInView, setIsInView] = useState(false);
  const imgRef = useRef(null);
  const containerRef = useRef(null);

  // Intersection Observer for lazy loading
  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsInView(true);
          observer.disconnect();
        }
      },
      { rootMargin: '50px', threshold: 0.01 }
    );

    if (containerRef.current) {
      observer.observe(containerRef.current);
    }

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

  // Reset states when src changes
  useEffect(() => {
    setIsLoaded(false);
    setHasError(false);
  }, [src]);

  const handleLoad = () => {
    setIsLoaded(true);
    onLoad?.();
  };

  const handleError = () => {
    setHasError(true);
    onError?.();
  };

  if (hasError && fallback) {
    return <>{fallback}</>;
  }

  return (
    <div
      ref={containerRef}
      className={`relative overflow-hidden ${className}`}
      style={{ backgroundColor: placeholderColor }}
    >
      {/* Loading shimmer */}
      <AnimatePresence>
        {!isLoaded && !hasError && (
          <motion.div
            className="absolute inset-0 bg-gradient-to-r from-surface-800/60 via-surface-700/40 to-surface-800/60"
            initial={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.3 }}
          >
            <motion.div
              className="absolute inset-0 bg-gradient-to-r from-transparent via-white/5 to-transparent"
              initial={{ x: '-100%' }}
              animate={{ x: '100%' }}
              transition={{
                duration: 1.5,
                repeat: Infinity,
                ease: 'linear',
              }}
            />
          </motion.div>
        )}
      </AnimatePresence>

      {/* Actual image */}
      {isInView && (
        <motion.img
          ref={imgRef}
          src={src}
          alt={alt}
          loading="lazy"
          onLoad={handleLoad}
          onError={handleError}
          className={`w-full h-full object-cover transition-transform duration-500 ease-out ${
            zoom ? 'group-hover:scale-105' : ''
          }`}
          initial={{ opacity: 0, scale: 1.1, filter: 'blur(20px)' }}
          animate={
            isLoaded
              ? { opacity: 1, scale: 1, filter: 'blur(0px)' }
              : { opacity: 0, scale: 1.1, filter: 'blur(20px)' }
          }
          transition={{ duration: 0.5, ease: 'easeOut' }}
        />
      )}

      {/* Error state */}
      {hasError && !fallback && (
        <motion.div
          className="absolute inset-0 flex items-center justify-center bg-surface-800/80"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
        >
          <div className="text-center text-surface-400">
            <i className="fa-solid fa-image text-3xl mb-2 opacity-50" />
            <p className="text-xs">Image unavailable</p>
          </div>
        </motion.div>
      )}
    </div>
  );
}

/**
 * GalleryImage - BlurImage with gallery navigation overlay
 */
export function GalleryImage({
  src,
  alt = '',
  className = '',
  currentIndex,
  totalCount,
  onPrev,
  onNext,
  onError,
  fallback,
}) {
  const [isHovered, setIsHovered] = useState(false);

  return (
    <div
      className={`group relative ${className}`}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      <BlurImage
        src={src}
        alt={alt}
        className="w-full h-full"
        onError={onError}
        fallback={fallback}
        zoom
      />

      {/* Gallery counter */}
      {totalCount > 1 && (
        <motion.div
          className="absolute top-3 right-3 px-3 py-1.5 rounded-full
                     bg-black/60 backdrop-blur-sm text-white/90
                     text-xs font-semibold tracking-wide
                     border border-white/10"
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
        >
          {currentIndex + 1}/{totalCount}
        </motion.div>
      )}

      {/* Navigation arrows */}
      <AnimatePresence>
        {totalCount > 1 && isHovered && (
          <>
            <motion.button
              type="button"
              className="absolute left-3 top-1/2 -translate-y-1/2
                         w-10 h-10 rounded-full
                         bg-black/50 backdrop-blur-sm
                         border border-white/15 text-white
                         flex items-center justify-center
                         hover:bg-accent/40 hover:border-accent/50
                         transition-colors duration-200"
              onClick={(e) => {
                e.stopPropagation();
                onPrev?.();
              }}
              initial={{ opacity: 0, x: -10 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -10 }}
              whileHover={{ scale: 1.1 }}
              whileTap={{ scale: 0.95 }}
            >
              <i className="fa-solid fa-chevron-left" />
            </motion.button>

            <motion.button
              type="button"
              className="absolute right-3 top-1/2 -translate-y-1/2
                         w-10 h-10 rounded-full
                         bg-black/50 backdrop-blur-sm
                         border border-white/15 text-white
                         flex items-center justify-center
                         hover:bg-accent/40 hover:border-accent/50
                         transition-colors duration-200"
              onClick={(e) => {
                e.stopPropagation();
                onNext?.();
              }}
              initial={{ opacity: 0, x: 10 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: 10 }}
              whileHover={{ scale: 1.1 }}
              whileTap={{ scale: 0.95 }}
            >
              <i className="fa-solid fa-chevron-right" />
            </motion.button>
          </>
        )}
      </AnimatePresence>

      {/* Gradient overlay */}
      <div className="absolute inset-x-0 bottom-0 h-24 bg-gradient-to-t from-black/40 to-transparent pointer-events-none" />
    </div>
  );
}

export default BlurImage;
