'use client'

import type { AdminMedia } from '@admin/types'
import { useFailedImageUrl } from '@admin/hooks/use-failed-image-url'
import { cn } from '@admin/utils/shared/cn'
import { FileText, Film, ImageOff } from 'lucide-react'
import Image from 'next/image'

interface MediaPreviewProps {
  media: AdminMedia
  isFilled?: boolean
  showMetadata?: boolean
}

export function MediaPreview({ media, isFilled = false, showMetadata = false }: MediaPreviewProps) {
  const { hasImageFailed, markImageFailed } = useFailedImageUrl(media.url)

  if (media.contentType.startsWith('image/') && !hasImageFailed) {
    return (
      <div className="relative flex size-full flex-col items-center justify-center overflow-hidden">
        <Image
          src={media.url}
          alt={media.alt || media.filename}
          className={cn({
            'object-cover': isFilled,
            'object-contain': !isFilled
          })}
          fill
          sizes="200px"
          unoptimized
          loading="lazy"
          decoding="async"
          draggable={false}
          onError={markImageFailed}
        />

        {showMetadata && (
          <div className="pointer-events-none absolute inset-x-0 bottom-0 z-10 flex w-full items-center justify-between gap-4 bg-[linear-gradient(to_top,color-mix(in_oklab,var(--primary)_86%,transparent)_0%,color-mix(in_oklab,var(--primary)_52%,transparent)_48%,transparent_100%)] px-3 py-2 text-left text-xs font-medium text-white">
            <p className="truncate">{media.filename}</p>
            <p className="shrink-0">
              {media.contentType} &middot; {(media.size / 1024).toFixed(1)} KB
            </p>
          </div>
        )}
      </div>
    )
  }

  if (media.contentType.startsWith('image/')) {
    return (
      <div className="flex size-full items-center justify-center border border-border/80 bg-background text-muted-foreground/30">
        <ImageOff strokeWidth={1} className="size-12" />
      </div>
    )
  }

  if (media.contentType.startsWith('video/')) {
    return (
      <div className="flex size-full items-center justify-center">
        <Film className="size-12 text-foreground" />
      </div>
    )
  }

  return (
    <div className="flex size-full items-center justify-center">
      <FileText className="size-12 text-foreground" />
    </div>
  )
}
