'use client';

import React, { useState, useCallback } from 'react';
import Image from 'next/image';

interface OptimizedImageProps {
  src: string;
  alt: string;
  width?: number;
  height?: number;
  className?: string;
  priority?: boolean;
  quality?: number;
  placeholder?: 'blur' | 'empty';
  blurDataURL?: string;
  sizes?: string;
  fill?: boolean;
  onLoad?: () => void;
  onError?: () => void;
}

/**
 * Optimized image component with enhanced loading and caching
 */
export function OptimizedImage({
  src,
  alt,
  width = 400,
  height = 400,
  className = '',
  priority = false,
  quality = 75,
  placeholder = 'blur',
  sizes = '(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw',
  fill = false,
  onLoad,
  onError,
  ...props
}: OptimizedImageProps) {
  const [isLoading, setIsLoading] = useState(true);
  const [hasError, setHasError] = useState(false);
  const [imageSrc, setImageSrc] = useState(src);

  // Generate blur placeholder
  const generateBlurDataURL = useCallback((w: number, h: number) => {
    return `data:image/svg+xml;base64,${Buffer.from(
      `<svg width="${w}" height="${h}" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <defs>
          <linearGradient id="g">
            <stop stop-color="#f3f4f6" offset="20%" />
            <stop stop-color="#e5e7eb" offset="50%" />
            <stop stop-color="#f3f4f6" offset="70%" />
          </linearGradient>
        </defs>
        <rect width="${w}" height="${h}" fill="url(#g)" />
      </svg>`
    ).toString('base64')}`;
  }, []);

  const handleLoad = useCallback(() => {
    setIsLoading(false);
    setHasError(false);
    onLoad?.();
  }, [onLoad]);

  const handleError = useCallback(() => {
    setIsLoading(false);
    setHasError(true);
    // Fallback to placeholder image
    setImageSrc('/images/placeholder-product.jpg');
    onError?.();
  }, [onError]);

  // Error fallback component
  if (hasError && imageSrc === '/images/placeholder-product.jpg') {
    return (
      <div 
        className={`bg-gray-200 flex items-center justify-center ${className}`}
        style={{ width: fill ? '100%' : width, height: fill ? '100%' : height }}
      >
        <svg 
          className="w-12 h-12 text-gray-400" 
          fill="none" 
          stroke="currentColor" 
          viewBox="0 0 24 24"
        >
          <path 
            strokeLinecap="round" 
            strokeLinejoin="round" 
            strokeWidth={2} 
            d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" 
          />
        </svg>
      </div>
    );
  }

  return (
    <div className={`relative overflow-hidden ${className}`}>
      <Image
        src={imageSrc}
        alt={alt}
        width={fill ? undefined : width}
        height={fill ? undefined : height}
        fill={fill}
        priority={priority}
        quality={quality}
        placeholder={placeholder}
        blurDataURL={generateBlurDataURL(width, height)}
        sizes={sizes}
        onLoad={handleLoad}
        onError={handleError}
        className={`transition-opacity duration-300 ${
          isLoading ? 'opacity-0' : 'opacity-100'
        }`}
        {...props}
      />
      
      {/* Loading overlay */}
      {isLoading && (
        <div className="absolute inset-0 bg-gray-200 animate-pulse flex items-center justify-center">
          <div className="w-8 h-8 border-2 border-gray-300 border-t-blue-600 rounded-full animate-spin" />
        </div>
      )}
    </div>
  );
}

/**
 * Product image with aspect ratio container
 */
export function ProductImage({
  src,
  alt,
  priority = false,
  className = '',
  ...props
}: Omit<OptimizedImageProps, 'width' | 'height' | 'fill'>) {
  return (
    <div className={`relative aspect-square overflow-hidden ${className}`}>
      <OptimizedImage
        src={src}
        alt={alt}
        fill
        priority={priority}
        sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 25vw"
        className="object-cover hover:scale-105 transition-transform duration-300"
        {...props}
      />
    </div>
  );
}

/**
 * Category image with overlay
 */
export function CategoryImage({
  src,
  alt,
  title,
  className = '',
  ...props
}: OptimizedImageProps & { title?: string }) {
  return (
    <div className={`relative aspect-[4/3] overflow-hidden rounded-lg ${className}`}>
      <OptimizedImage
        src={src}
        alt={alt}
        fill
        sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
        className="object-cover"
        {...props}
      />
      
      {title && (
        <div className="absolute inset-0 bg-black bg-opacity-40 flex items-center justify-center">
          <h3 className="text-white text-xl font-semibold text-center px-4">
            {title}
          </h3>
        </div>
      )}
    </div>
  );
}

/**
 * Hero image with full viewport support
 */
export function HeroImage({
  src,
  alt,
  children,
  className = '',
  ...props
}: OptimizedImageProps & { children?: React.ReactNode }) {
  return (
    <div className={`relative h-96 md:h-[500px] overflow-hidden rounded-lg ${className}`}>
      <OptimizedImage
        src={src}
        alt={alt}
        fill
        priority
        quality={90}
        sizes="100vw"
        className="object-cover"
        {...props}
      />
      
      {children && (
        <div className="absolute inset-0 bg-black bg-opacity-30 flex items-center justify-center">
          {children}
        </div>
      )}
    </div>
  );
}

export default OptimizedImage;