"use client"

import React, { useState, useRef, useEffect } from "react"
import { motion, AnimatePresence } from "framer-motion"
import { Card, CardContent } from "../ui/card"
import { Button } from "../ui/button"
import { MoonUIBadgePro as Badge } from "../ui/badge"
import { MoonUISkeletonPro as Skeleton } from "../ui/skeleton"
import { cn } from "../../lib/utils"
import { 
  Image as ImageIcon, 
  Maximize2, 
  Download, 
  Eye, 
  EyeOff, 
  RotateCw,
  ZoomIn,
  ZoomOut,
  X,
  Lock,
  Sparkles,
  Loader2
} from "lucide-react"
import { useSubscription } from "../../hooks/use-subscription"

interface OptimizedImageProps {
  src: string
  alt: string
  width?: number
  height?: number
  quality?: number
  format?: "webp" | "avif" | "jpeg" | "png" | "auto"
  lazy?: boolean
  blur?: boolean
  priority?: boolean
  sizes?: string
  srcSet?: string
  fallbackSrc?: string
  showPreview?: boolean
  showZoom?: boolean
  showDownload?: boolean
  showInfo?: boolean
  zoomLevel?: number
  className?: string
  onLoad?: () => void
  onError?: (error: Error) => void
  onZoom?: (level: number) => void
}

const OptimizedImageInternal: React.FC<OptimizedImageProps> = ({
  src,
  alt,
  width,
  height,
  quality = 75,
  format = "auto",
  lazy = true,
  blur = true,
  priority = false,
  sizes,
  srcSet,
  fallbackSrc,
  showPreview = true,
  showZoom = true,
  showDownload = true,
  showInfo = true,
  zoomLevel = 1,
  className,
  onLoad,
  onError,
  onZoom
}) => {
  const [isLoaded, setIsLoaded] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [hasError, setHasError] = useState(false)
  const [isPreviewOpen, setIsPreviewOpen] = useState(false)
  const [currentZoom, setCurrentZoom] = useState(zoomLevel)
  const [imageInfo, setImageInfo] = useState<{
    naturalWidth: number
    naturalHeight: number
    fileSize?: number
  } | null>(null)
  const [showImageInfo, setShowImageInfo] = useState(false)
  
  const imgRef = useRef<HTMLImageElement>(null)
  const previewRef = useRef<HTMLImageElement>(null)

  // Generate optimized image URL
  const getOptimizedSrc = (originalSrc: string, options: {
    width?: number
    height?: number
    quality?: number
    format?: string
  } = {}) => {
    // This would typically integrate with image optimization services
    // like Cloudinary, ImageKit, or Next.js Image Optimization
    let optimizedUrl = originalSrc
    
    // Example for a generic image optimization service
    const params = new URLSearchParams()
    if (options.width) params.set('w', options.width.toString())
    if (options.height) params.set('h', options.height.toString())
    if (options.quality) params.set('q', options.quality.toString())
    if (options.format && options.format !== 'auto') params.set('f', options.format)
    
    // For demo purposes, we'll just return the original URL
    // In production, you'd construct an optimized URL like:
    // return `https://your-image-service.com/transform?${params}&url=${encodeURIComponent(originalSrc)}`
    
    return optimizedUrl
  }

  const optimizedSrc = getOptimizedSrc(src, { width, height, quality, format })

  const handleImageLoad = () => {
    setIsLoaded(true)
    setIsLoading(false)
    
    if (imgRef.current) {
      setImageInfo({
        naturalWidth: imgRef.current.naturalWidth,
        naturalHeight: imgRef.current.naturalHeight
      })
    }
    
    onLoad?.()
  }

  const handleImageError = () => {
    setHasError(true)
    setIsLoading(false)
    onError?.(new Error("Failed to load image"))
  }

  const handleDownload = async () => {
    try {
      const response = await fetch(optimizedSrc)
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = alt || 'image'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    } catch (error) {
      console.error('Download failed:', error)
    }
  }

  const handleZoomIn = () => {
    const newZoom = Math.min(currentZoom * 1.2, 5)
    setCurrentZoom(newZoom)
    onZoom?.(newZoom)
  }

  const handleZoomOut = () => {
    const newZoom = Math.max(currentZoom / 1.2, 0.2)
    setCurrentZoom(newZoom)
    onZoom?.(newZoom)
  }

  const resetZoom = () => {
    setCurrentZoom(1)
    onZoom?.(1)
  }

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // Generate srcSet for responsive images
  const generateSrcSet = () => {
    if (srcSet) return srcSet
    
    if (!width) return undefined
    
    const widths = [width * 0.5, width, width * 1.5, width * 2]
    return widths
      .map(w => `${getOptimizedSrc(src, { width: Math.round(w), quality })} ${Math.round(w)}w`)
      .join(', ')
  }

  return (
    <>
      <div className={cn("relative group overflow-hidden", className)}>
        {/* Loading/Error States */}
        {isLoading && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="absolute inset-0 flex items-center justify-center bg-muted"
          >
            {blur ? (
              <Skeleton className="w-full h-full" />
            ) : (
              <div className="text-center">
                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground mx-auto mb-2" />
                <p className="text-sm text-muted-foreground">Loading image...</p>
              </div>
            )}
          </motion.div>
        )}

        {hasError && (
          <div className="absolute inset-0 flex items-center justify-center bg-muted">
            <div className="text-center">
              <ImageIcon className="h-12 w-12 text-muted-foreground mx-auto mb-2" />
              <p className="text-sm text-muted-foreground">Failed to load image</p>
              {fallbackSrc && (
                <img
                  src={fallbackSrc}
                  alt={alt}
                  className="mt-2 max-w-full max-h-32 object-contain"
                />
              )}
            </div>
          </div>
        )}

        {/* Optimized Image */}
        <motion.img
          ref={imgRef}
          src={optimizedSrc}
          alt={alt}
          width={width}
          height={height}
          sizes={sizes}
          srcSet={generateSrcSet()}
          loading={lazy ? "lazy" : priority ? "eager" : "lazy"}
          onLoad={handleImageLoad}
          onError={handleImageError}
          className={cn(
            "w-full h-full object-cover transition-opacity duration-300",
            isLoaded ? "opacity-100" : "opacity-0"
          )}
          initial={{ scale: blur && !isLoaded ? 1.1 : 1 }}
          animate={{ scale: 1 }}
          transition={{ duration: 0.3 }}
        />

        {/* Image Controls Overlay */}
        <AnimatePresence>
          {isLoaded && (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors duration-200"
            >
              <div className="absolute top-2 right-2 flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                {showInfo && (
                  <Button
                    size="sm"
                    variant="secondary"
                    className="h-8 w-8 p-0"
                    onClick={() => setShowImageInfo(!showImageInfo)}
                  >
                    {showImageInfo ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </Button>
                )}
                
                {showDownload && (
                  <Button
                    size="sm"
                    variant="secondary"
                    className="h-8 w-8 p-0"
                    onClick={handleDownload}
                  >
                    <Download className="h-4 w-4" />
                  </Button>
                )}
                
                {showPreview && (
                  <Button
                    size="sm"
                    variant="secondary"
                    className="h-8 w-8 p-0"
                    onClick={() => setIsPreviewOpen(true)}
                  >
                    <Maximize2 className="h-4 w-4" />
                  </Button>
                )}
              </div>

              {/* Image Info */}
              <AnimatePresence>
                {showImageInfo && imageInfo && (
                  <motion.div
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: 10 }}
                    className="absolute bottom-2 left-2 bg-black/80 text-white text-xs p-2 rounded"
                  >
                    <div>{imageInfo.naturalWidth} × {imageInfo.naturalHeight}px</div>
                    <div>Quality: {quality}%</div>
                    <div>Format: {format}</div>
                  </motion.div>
                )}
              </AnimatePresence>
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      {/* Full Screen Preview Modal */}
      <AnimatePresence>
        {isPreviewOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4"
            onClick={() => setIsPreviewOpen(false)}
          >
            <div className="relative max-w-full max-h-full" onClick={(e) => e.stopPropagation()}>
              {/* Preview Controls */}
              <div className="absolute top-4 right-4 flex gap-2 z-10">
                {showZoom && (
                  <>
                    <Button
                      size="sm"
                      variant="secondary"
                      onClick={handleZoomOut}
                      disabled={currentZoom <= 0.2}
                    >
                      <ZoomOut className="h-4 w-4" />
                    </Button>
                    
                    <Badge variant="secondary" className="px-2">
                      {Math.round(currentZoom * 100)}%
                    </Badge>
                    
                    <Button
                      size="sm"
                      variant="secondary"
                      onClick={handleZoomIn}
                      disabled={currentZoom >= 5}
                    >
                      <ZoomIn className="h-4 w-4" />
                    </Button>
                    
                    <Button
                      size="sm"
                      variant="secondary"
                      onClick={resetZoom}
                    >
                      <RotateCw className="h-4 w-4" />
                    </Button>
                  </>
                )}
                
                <Button
                  size="sm"
                  variant="secondary"
                  onClick={() => setIsPreviewOpen(false)}
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>

              {/* Preview Image */}
              <motion.img
                ref={previewRef}
                src={optimizedSrc}
                alt={alt}
                className="max-w-full max-h-full object-contain"
                style={{
                  transform: `scale(${currentZoom})`,
                  transformOrigin: 'center center'
                }}
                initial={{ scale: 0.9 }}
                animate={{ scale: currentZoom }}
                transition={{ duration: 0.2 }}
              />
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  )
}

export const OptimizedImage: React.FC<OptimizedImageProps> = ({ className, ...props }) => {
  // Check if we're in docs mode or have pro access
  const { hasProAccess, isLoading } = useSubscription()
  
  // In docs mode, always show the component
  
  // If not in docs mode and no pro access, show upgrade prompt
  if (!isLoading && !hasProAccess) {
    return (
      <Card className={cn("w-fit", className)}>
        <CardContent className="py-6 text-center">
          <div className="space-y-4">
            <div className="rounded-full bg-purple-100 dark:bg-purple-900/30 p-3 w-fit mx-auto">
              <Lock className="h-6 w-6 text-purple-600 dark:text-purple-400" />
            </div>
            <div>
              <h3 className="font-semibold text-sm mb-2">Pro Feature</h3>
              <p className="text-muted-foreground text-xs mb-4">
                Optimized Image is available exclusively to MoonUI Pro subscribers.
              </p>
              <a href="/pricing">
                <Button size="sm">
                  <Sparkles className="mr-2 h-4 w-4" />
                  Upgrade to Pro
                </Button>
              </a>
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  return <OptimizedImageInternal className={className} {...props} />
}

export type { OptimizedImageProps }