import { useEffect, useState } from 'react'
import api from '../api/client'

interface Props {
  questionId: string
  variant?: 'original' | 'annotated' | 'cropped'
  className?: string
  alt?: string
  style?: React.CSSProperties
}

export default function AuthenticatedImage({
  questionId,
  variant = 'original',
  className,
  alt = '题目',
  style,
}: Props) {
  const [src, setSrc] = useState<string | null>(null)
  const [failed, setFailed] = useState(false)

  useEffect(() => {
    let objectUrl: string | null = null
    let cancelled = false

    const load = async (path: string, fallback?: string) => {
      try {
        const res = await api.get(path, { responseType: 'blob' })
        if (cancelled) return
        objectUrl = URL.createObjectURL(res.data)
        setSrc(objectUrl)
        setFailed(false)
      } catch {
        if (fallback && !cancelled) {
          await load(fallback)
        } else if (!cancelled) {
          setFailed(true)
        }
      }
    }

    const annotatedPath = `/wrong-questions/${questionId}/annotated-image`
    const croppedPath = `/wrong-questions/${questionId}/cropped-image`
    const originalPath = `/wrong-questions/${questionId}/image`

    if (variant === 'annotated') {
      load(annotatedPath, originalPath)
    } else if (variant === 'cropped') {
      load(croppedPath, annotatedPath)
    } else {
      load(originalPath)
    }

    return () => {
      cancelled = true
      if (objectUrl) URL.revokeObjectURL(objectUrl)
    }
  }, [questionId, variant])

  if (failed) {
    return (
      <div
        className={className}
        style={{
          ...style,
          background: '#fafafa',
          color: '#999',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: 12,
        }}
      >
        图片加载失败
      </div>
    )
  }

  if (!src) {
    return <div className={className} style={{ ...style, background: '#fafafa' }} />
  }

  return <img src={src} alt={alt} className={className} style={style} />
}
