'use client'

import React from 'react'
import { cn } from '@/lib/utils'

/**
 * Image Component for MDX Documentation
 * 
 * Supports resizing via wsrv.nl image proxy for optimization.
 */

interface ImageProps {
  src: string
  alt: string
  width?: number
  height?: number
  maxWidth?: number
  maxHeight?: number
  caption?: string
  className?: string
  rounded?: boolean
  shadow?: boolean
  border?: boolean
  align?: 'left' | 'center' | 'right'
  optimize?: boolean // Enable wsrv.nl optimization (default: true for external images)
  quality?: number // Image quality 1-100 (default: 80)
}

/**
 * Get resized image URL using wsrv.nl proxy
 */
function getResizedImageUrl(
  imageUrl: string,
  options: {
    width?: number
    height?: number
    maxWidth?: number
    maxHeight?: number
    quality?: number
  } = {}
): string {
  const { width, height, maxWidth, maxHeight, quality = 80 } = options

  // Skip if already a wsrv.nl URL
  if (imageUrl.startsWith('https://wsrv.nl')) {
    return imageUrl
  }

  // For data URLs, we can't use wsrv.nl
  if (imageUrl.startsWith('data:')) {
    return imageUrl
  }

  // For relative URLs (local images), don't proxy
  if (imageUrl.startsWith('/') || imageUrl.startsWith('./') || imageUrl.startsWith('../')) {
    return imageUrl
  }

  // Build wsrv.nl URL
  const proxyUrl = new URL('https://wsrv.nl/')
  proxyUrl.searchParams.set('url', imageUrl)

  // Set dimensions
  if (width) {
    proxyUrl.searchParams.set('w', width.toString())
  } else if (maxWidth) {
    proxyUrl.searchParams.set('w', maxWidth.toString())
  }

  if (height) {
    proxyUrl.searchParams.set('h', height.toString())
  } else if (maxHeight) {
    proxyUrl.searchParams.set('h', maxHeight.toString())
  }

  // If only max dimensions are set, use fit=inside to maintain aspect ratio
  if ((maxWidth || maxHeight) && !width && !height) {
    proxyUrl.searchParams.set('fit', 'inside')
    proxyUrl.searchParams.set('n', '-1') // Don't upscale
  }

  // Quality and format
  proxyUrl.searchParams.set('q', quality.toString())

  return proxyUrl.toString()
}

export function Image({
  src,
  alt,
  width,
  height,
  maxWidth,
  maxHeight,
  caption,
  className,
  rounded = true,
  shadow = false,
  border = false,
  align = 'center',
  optimize = true,
  quality = 80,
}: ImageProps) {
  // Determine if we should optimize
  const isExternalImage = src.startsWith('http://') || src.startsWith('https://')
  const shouldOptimize = optimize && isExternalImage

  // Get the final image URL
  const imageSrc = shouldOptimize
    ? getResizedImageUrl(src, { width, height, maxWidth, maxHeight, quality })
    : src

  const alignmentClasses = {
    left: 'mr-auto',
    center: 'mx-auto',
    right: 'ml-auto',
  }

  const imageElement = (
    // eslint-disable-next-line @next/next/no-img-element
    <img
      src={imageSrc}
      alt={alt}
      width={width}
      height={height}
      style={{
        maxWidth: maxWidth ? `${maxWidth}px` : '100%',
        maxHeight: maxHeight ? `${maxHeight}px` : undefined,
        height: 'auto',
      }}
      className={cn(
        'docs-image',
        rounded && 'rounded-lg',
        shadow && 'shadow-lg',
        border && 'border border-border',
        alignmentClasses[align],
        className
      )}
      loading="lazy"
    />
  )

  if (caption) {
    return (
      <figure className={cn('docs-image-figure my-6', alignmentClasses[align])}>
        {imageElement}
        <figcaption className="docs-image-caption mt-2 text-center text-sm text-muted-foreground">
          {caption}
        </figcaption>
      </figure>
    )
  }

  return <div className={cn('docs-image-wrapper my-4', alignmentClasses[align])}>{imageElement}</div>
}

/**
 * Screenshot component - convenience wrapper with default styling
 */
export function Screenshot({
  src,
  alt,
  caption,
  maxWidth = 800,
  className,
  ...props
}: Omit<ImageProps, 'shadow' | 'border' | 'rounded'>) {
  return (
    <Image
      src={src}
      alt={alt}
      caption={caption}
      maxWidth={maxWidth}
      rounded
      shadow
      border
      className={cn('docs-screenshot', className)}
      {...props}
    />
  )
}

/**
 * Logo component - for displaying logos without optimization artifacts
 */
export function Logo({
  src,
  alt,
  width = 200,
  height,
  className,
  ...props
}: Omit<ImageProps, 'optimize' | 'quality' | 'shadow' | 'rounded' | 'border'>) {
  return (
    <Image
      src={src}
      alt={alt}
      width={width}
      height={height}
      optimize={false}
      rounded={false}
      shadow={false}
      border={false}
      className={cn('docs-logo', className)}
      {...props}
    />
  )
}

/**
 * Icon component - small images/icons
 */
export function Icon({
  src,
  alt,
  size = 24,
  className,
}: {
  src: string
  alt: string
  size?: number
  className?: string
}) {
  return (
    // eslint-disable-next-line @next/next/no-img-element
    <img
      src={src}
      alt={alt}
      width={size}
      height={size}
      className={cn('docs-icon inline-block', className)}
      loading="lazy"
    />
  )
}
