'use client'

import React, { useState, useEffect } from 'react'
import { AlertTriangle } from 'lucide-react'

interface Base64ImageProps {
  src: string
  alt?: string
  className?: string
  onClick?: () => void
  onLoad?: () => void
  onError?: () => void
}

export function Base64Image({ 
  src, 
  alt = "Generated image", 
  className = "", 
  onClick,
  onLoad,
  onError 
}: Base64ImageProps) {
  const [isLoading, setIsLoading] = useState(true)
  const [hasError, setHasError] = useState(false)
  const [imageSrc, setImageSrc] = useState<string>('')

  useEffect(() => {
    if (!src) {
      setHasError(true)
      setIsLoading(false)
      return
    }

    // 如果是完整的 data URL，直接使用
    if (src.startsWith('data:image/')) {
      setImageSrc(src)
      setIsLoading(false)
    }
    // 如果是纯 base64 数据，添加 data URL 前缀
    else if (src.length > 100 && !src.startsWith('http')) {
      // 假设是 PNG 格式，可以根据需要调整
      setImageSrc(`data:image/png;base64,${src}`)
      setIsLoading(false)
    }
    // 如果是 URL，直接使用
    else if (src.startsWith('http')) {
      setImageSrc(src)
      setIsLoading(false)
    }
    else {
      setHasError(true)
      setIsLoading(false)
    }
  }, [src])

  const handleLoad = () => {
    setIsLoading(false)
    setHasError(false)
    onLoad?.()
  }

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

  if (isLoading) {
    return (
      <div className={`flex items-center justify-center bg-gray-100 dark:bg-gray-800 rounded-lg ${className}`}>
        <div className="flex flex-col items-center space-y-2 p-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
          <span className="text-sm text-gray-500">加载图片中...</span>
        </div>
      </div>
    )
  }

  if (hasError || !imageSrc) {
    return (
      <div className={`flex items-center justify-center bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-800 rounded-lg ${className}`}>
        <div className="flex flex-col items-center space-y-2 p-8">
          <AlertTriangle className="h-8 w-8 text-red-500" />
          <span className="text-sm text-red-600 dark:text-red-400">图片加载失败</span>
          <span className="text-xs text-gray-500">请检查图片数据格式</span>
        </div>
      </div>
    )
  }

  return (
    <img
      src={imageSrc}
      alt={alt}
      className={className}
      onLoad={handleLoad}
      onError={handleError}
      onClick={onClick}
      style={{ cursor: onClick ? 'pointer' : 'default' }}
    />
  )
}