import React, { useState } from 'react'

import { optimizeMessagingAttachmentUrl } from '../../utils/cdnImageUrl'

import MediaPlayer, { type MediaPlayerProps } from './MediaPlayer'
import { renderTypeIcon } from './utils/icons'
import { getSourceType } from './utils/mimeType'

export type AttachmentThumbnailVariant = 'light' | 'dark'

export interface AttachmentThumbnailProps {
  mimeType: string
  sourceUrl?: string
  thumbnailUrl?: string
  title?: string
  variant: AttachmentThumbnailVariant
  /** Extra props passed to MediaPlayer when source is video or audio. */
  mediaPlayerProps?: Partial<
    Pick<
      MediaPlayerProps,
      'autoPlay' | 'loop' | 'muted' | 'controls' | 'onContainerClick'
    >
  >
  /**
   * When true (Visitor unlocked image/document), use aspect-video + object-contain fade-in.
   */
  containedImage?: boolean
}

const placeholderIconClass = (variant: AttachmentThumbnailVariant) =>
  variant === 'dark' ? 'size-12 text-white/20' : 'size-12 text-black/20'

const posterShellClass = (variant: AttachmentThumbnailVariant) =>
  variant === 'dark'
    ? 'aspect-video overflow-hidden bg-white/10'
    : 'aspect-video overflow-hidden bg-black/5'

/**
 * Renders the media preview area for attachment cards (LockedAttachment, MediaMessage).
 * Overlays (dim, lock, eye toggle) are composed by the parent.
 */
const AttachmentThumbnail: React.FC<AttachmentThumbnailProps> = ({
  mimeType,
  sourceUrl,
  thumbnailUrl,
  title,
  variant,
  mediaPlayerProps,
  containedImage = false,
}) => {
  const sourceType = getSourceType(mimeType)
  const [sourceReady, setSourceReady] = useState(false)
  const optimizedSourceUrl = optimizeMessagingAttachmentUrl(sourceUrl)
  const optimizedThumbnailUrl = optimizeMessagingAttachmentUrl(thumbnailUrl)

  if (sourceUrl && (sourceType === 'video' || sourceType === 'audio')) {
    return (
      <MediaPlayer
        source={sourceUrl}
        mimeType={mimeType}
        poster={optimizedThumbnailUrl}
        controls
        {...mediaPlayerProps}
      />
    )
  }

  if (sourceUrl && sourceType === 'image') {
    if (containedImage) {
      return (
        <div className={`relative ${posterShellClass(variant)}`}>
          <img
            src={optimizedSourceUrl ?? sourceUrl}
            alt={title ?? ''}
            className={`absolute inset-0 h-full w-full object-contain transition-opacity duration-300 ${sourceReady ? 'opacity-100' : 'opacity-0'}`}
            draggable={false}
            onLoad={() => setSourceReady(true)}
          />
        </div>
      )
    }
    return (
      <img
        src={optimizedSourceUrl ?? sourceUrl}
        alt={title ?? ''}
        className="block w-full"
        draggable={false}
      />
    )
  }

  if (sourceUrl && sourceType === 'document') {
    if (thumbnailUrl) {
      if (containedImage) {
        return (
          <div className={`relative ${posterShellClass(variant)}`}>
            <img
              src={optimizedThumbnailUrl ?? thumbnailUrl}
              alt={title ?? ''}
              className={`absolute inset-0 h-full w-full object-contain transition-opacity duration-300 ${sourceReady ? 'opacity-100' : 'opacity-0'}`}
              draggable={false}
              onLoad={() => setSourceReady(true)}
            />
          </div>
        )
      }
      return (
        <img
          src={optimizedThumbnailUrl ?? thumbnailUrl}
          alt=""
          className="block w-full"
          draggable={false}
        />
      )
    }
    return (
      <div
        className={`flex aspect-video w-full items-center justify-center ${variant === 'dark' ? 'bg-white/10' : 'bg-black/5'}`}
      >
        {renderTypeIcon(mimeType, {
          className: placeholderIconClass(variant),
          weight: 'regular',
        })}
      </div>
    )
  }

  // Poster-only or empty (no sourceUrl)
  if (thumbnailUrl) {
    return (
      <div className={`relative ${posterShellClass(variant)}`}>
        <img
          src={optimizedThumbnailUrl ?? thumbnailUrl}
          alt={title ?? ''}
          draggable={false}
          className="absolute inset-0 h-full w-full object-cover"
        />
      </div>
    )
  }

  return (
    <div
      className={`flex aspect-video w-full items-center justify-center ${variant === 'dark' ? 'bg-white/10' : 'bg-black/5'}`}
    >
      {renderTypeIcon(mimeType, {
        className: placeholderIconClass(variant),
        weight: 'regular',
      })}
    </div>
  )
}

export default AttachmentThumbnail
