import { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { fetchAPI, postAPI, deleteAPI } from '../api/client'
import { useToast } from '../components/Toast'
import ConfirmModal from '../components/ConfirmModal'
import StatusBadge from '../components/StatusBadge'
import ErrorBanner from '../components/ErrorBanner'
import ReleaseSearchResults from '../components/ReleaseSearchResults'

interface Media {
  id: number
  media_type: string
  title: string
  sort_title: string
  original_title: string | null
  overview: string | null
  year: number | null
  status: string
  monitored: boolean
  external_ids: Record<string, string>
  metadata: Record<string, unknown>
  images: Array<{ url: string; type: string; width: number; height: number }>
  quality_profile_id: number | null
  current_quality: { resolution?: string; source?: string } | null
  desired_quality: { resolution?: string; source?: string } | null
  quality_upgrade_needed: boolean
  added_at: string
  updated_at: string
}

interface MediaFile {
  id: number
  media_id: number
  path: string
  original_path: string | null
  file_name: string
  file_size: number
  quality: { resolution?: string; source?: string; codec?: string } | null
  codec: string | null
  resolution: string | null
  source: string | null
  transcode_status: string
  created_at: string
}

interface MediaRelation {
  id: number
  parent_id: number
  child_id: number
  relation: string
  position: number | null
  season: number | null
}

interface MediaDetail {
  media: Media
  files: MediaFile[]
  relations: MediaRelation[]
}

interface QualityProfileInfo {
  id: number
  name: string
  cutoff_quality: Record<string, unknown>
  allowed_qualities: Record<string, unknown>[]
}

interface SubtitleInfo {
  file_name: string
  language: string
  language_code: string
  hi: boolean
  forced: boolean
  source: string
}

interface FileWithSubtitles extends MediaFile {
  subtitles: SubtitleInfo[]
}

interface EpisodeInfo {
  media_id: number
  title: string
  season: number
  episode: number
  status: string
  monitored: boolean
  air_date: string | null
  has_file: boolean
  quality: { resolution?: string } | null
}

interface MediaHistoryItem {
  id: number
  event_type: string
  title: string
  description: string | null
  data: Record<string, unknown>
  created_at: string
}

interface FullMediaDetail {
  media: MediaDetail
  quality_profile: QualityProfileInfo | null
  files_with_subtitles: FileWithSubtitles[]
  episodes: EpisodeInfo[]
  history: MediaHistoryItem[]
}

interface ReleaseSearchResult {
  title: string
  guid: string
  size: number
  pub_date: string
  indexer_name: string
  indexer_priority: number
  quality: {
    title: string
    resolution: string
    source: string
    video_codec: string
    release_group: string
    parse_warning: boolean
  }
  quality_tier: { name: string; rank: number; resolution: string } | null
  seeders: number
  peers: number
  category: string
  download_url: string
  source_indexers: string[]
}

interface SubtitleSearchResult {
  id: string
  file_name: string
  language: string
  language_code: string
  hi: boolean
  forced: boolean
  download_count: number
  release_name: string
  provider: string
}

function eventTypeBadge(type: string): { label: string; className: string } {
  switch (type) {
    case 'grab':
      return { label: 'Grab', className: 'bg-blue-600' }
    case 'import':
      return { label: 'Import', className: 'bg-green-600' }
    case 'download_complete':
      return { label: 'Download', className: 'bg-green-600' }
    case 'download_failed':
      return { label: 'Failed', className: 'bg-red-600' }
    case 'quality_upgrade':
      return { label: 'Upgrade', className: 'bg-purple-600' }
    case 'safety_block':
      return { label: 'Blocked', className: 'bg-orange-600' }
    case 'error':
      return { label: 'Error', className: 'bg-red-600' }
    default:
      return { label: 'Info', className: 'bg-gray-600' }
  }
}

function formatTimeAgo(dateStr: string): string {
  const diff = Date.now() - new Date(dateStr).getTime()
  const minutes = Math.floor(diff / 60000)
  if (minutes < 60) return `${minutes}m ago`
  const hours = Math.floor(minutes / 60)
  if (hours < 24) return `${hours}h ago`
  const days = Math.floor(hours / 24)
  return `${days}d ago`
}

function formatFileSize(bytes: number): string {
  if (bytes >= 1024 * 1024 * 1024) {
    return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`
  }
  if (bytes >= 1024 * 1024) {
    return `${(bytes / 1024 / 1024).toFixed(1)} MB`
  }
  return `${(bytes / 1024).toFixed(0)} KB`
}

type TabKey = 'overview' | 'search' | 'files' | 'episodes' | 'history'

export default function MediaDetail() {
  const { type, id } = useParams<{ type: string; id: string }>()
  const navigate = useNavigate()

  const [detail, setDetail] = useState<FullMediaDetail | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState<TabKey>('overview')
  const [searchResults, setSearchResults] = useState<ReleaseSearchResult[]>([])
  const [searchLoading, setSearchLoading] = useState(false)
  const [searchError, setSearchError] = useState<string | null>(null)
  const { showToast } = useToast()
  const [subtitleSearchFile, setSubtitleSearchFile] = useState<FileWithSubtitles | null>(null)
  const [subtitleResults, setSubtitleResults] = useState<SubtitleSearchResult[]>([])
  const [subtitleSearchLoading, setSubtitleSearchLoading] = useState(false)
  const [subtitleDownloading, setSubtitleDownloading] = useState<Set<string>>(new Set())
  const [extracting, setExtracting] = useState(false)
  const [refreshing, setRefreshing] = useState(false)
  const [showDeleteModal, setShowDeleteModal] = useState(false)

  useEffect(() => {
    if (!type || !id) return
    setLoading(true)
    setError(null)
    fetchAPI<FullMediaDetail>(`/api/media/${type}/${id}/detail`)
      .then(res => setDetail(res))
      .catch(err => setError(err.message || 'Failed to load media detail'))
      .finally(() => setLoading(false))
  }, [type, id])

  useEffect(() => {
    if (!type || !id || activeTab !== 'search') return
    const media = detail?.media.media
    if (!media) return
    setSearchLoading(true)
    setSearchError(null)
    const query = encodeURIComponent(media.title)
    fetchAPI<{ data: ReleaseSearchResult[]; total: number }>(`/api/releases/search?query=${query}&media_type=${media.media_type}`)
      .then(res => setSearchResults(res.data ?? []))
      .catch(err => setSearchError(err.message || 'Search failed'))
      .finally(() => setSearchLoading(false))
  }, [activeTab, type, id, detail?.media.media])

  const searchSubtitles = async (file: FileWithSubtitles) => {
    if (!type || !id) return
    setSubtitleSearchFile(file)
    setSubtitleSearchLoading(true)
    setSubtitleResults([])
    try {
      const res = await fetchAPI<{ data: SubtitleSearchResult[] }>(
        `/api/media/${type}/${id}/subtitles/search?languages=en`
      )
      setSubtitleResults(res.data ?? [])
    } catch {
      showToast('Failed to search subtitles')
    } finally {
      setSubtitleSearchLoading(false)
    }
  }

  const downloadSub = async (result: SubtitleSearchResult) => {
    if (!type || !id) return
    setSubtitleDownloading(prev => new Set(prev).add(result.id))
    try {
      await postAPI(`/api/media/${type}/${id}/subtitles/download`, {
        subtitle_id: result.id,
        language_code: result.language_code,
        hi: result.hi,
        forced: result.forced,
      })
      showToast(`✓ Downloaded ${result.language} subtitle`)
      // Refresh media detail to show new subtitle
      const refreshed = await fetchAPI<FullMediaDetail>(`/api/media/${type}/${id}/detail`)
      setDetail(refreshed)
      setSubtitleResults([])
      setSubtitleSearchFile(null)
    } catch {
      showToast('Failed to download subtitle')
    } finally {
      setSubtitleDownloading(prev => {
        const next = new Set(prev)
        next.delete(result.id)
        return next
      })
    }
  }

  const extractSubs = async () => {
    if (!type || !id) return
    setExtracting(true)
    try {
      await postAPI(`/api/media/${type}/${id}/subtitles/extract`, {})
      showToast('✓ Subtitles extracted')
      const refreshed = await fetchAPI<FullMediaDetail>(`/api/media/${type}/${id}/detail`)
      setDetail(refreshed)
    } catch {
      showToast('Failed to extract subtitles')
    } finally {
      setExtracting(false)
    }
  }

  const handleRefreshMetadata = async () => {
    if (!type || !id) return
    setRefreshing(true)
    try {
      await postAPI(`/api/media/${type}/${id}/refresh-metadata`, {})
      showToast('✓ Metadata refreshed')
      const refreshed = await fetchAPI<FullMediaDetail>(`/api/media/${type}/${id}/detail`)
      setDetail(refreshed)
    } catch {
      showToast('Failed to refresh metadata')
    } finally {
      setRefreshing(false)
    }
  }

  const handleDeleteMedia = async () => {
    if (!type || !id) return
    setShowDeleteModal(false)
    try {
      await deleteAPI(`/api/media/${type}/${id}`)
      showToast('✓ Media deleted')
      navigate('/library')
    } catch {
      showToast('Failed to delete media')
    }
  }

  if (loading) {
    return (
      <div className="animate-pulse space-y-4">
        <div className="h-8 bg-gray-800 rounded w-1/3" />
        <div className="h-64 bg-gray-800 rounded" />
      </div>
    )
  }

  if (error) {
    return <ErrorBanner error={error} onRetry={() => window.location.reload()} />
  }

  if (!detail) return null

  const media = detail.media.media
  const posterImage = detail.media.media.images?.find(i => i.type === 'poster')
  const isSeries = media.media_type === 'series'

  const metadata = media.metadata as Record<string, unknown> | null
  const tmdbRating = (metadata?.tmdb_rating as number) ?? null
  const genres = (metadata?.genres as string[]) ?? []

  const totalSize = detail.files_with_subtitles.reduce((sum, f) => sum + f.file_size, 0)

  const tabs: { key: TabKey; label: string }[] = [
    { key: 'overview', label: 'Overview' },
    { key: 'search', label: 'Search' },
    { key: 'files', label: 'Files' },
    ...(isSeries ? [{ key: 'episodes' as TabKey, label: 'Episodes' }] : []),
    { key: 'history', label: 'History' },
  ]

  // Group episodes by season
  const seasons: Record<number, EpisodeInfo[]> = {}
  if (isSeries && detail.episodes) {
    for (const ep of detail.episodes) {
      if (!seasons[ep.season]) seasons[ep.season] = []
      seasons[ep.season].push(ep)
    }
  }

  return (
    <div>
      {/* Header */}
      <div className="flex items-center gap-4 mb-6">
        <button
          onClick={() => navigate('/library')}
          className="text-sm text-indigo-400 hover:text-indigo-300 transition-colors"
        >
          ← Back to Library
        </button>
        <div className="flex items-center gap-2">
          <h2 className="text-2xl font-semibold text-gray-100">{media.title}</h2>
          <span className="px-2 py-0.5 rounded text-xs font-medium bg-gray-800 text-gray-400 capitalize">
            {media.media_type}
          </span>
        </div>
        <div className="ml-auto flex items-center gap-3">
          <button
            onClick={handleRefreshMetadata}
            disabled={refreshing}
            className="bg-gray-700 hover:bg-gray-600 disabled:opacity-50 px-4 py-2 rounded text-sm font-semibold min-h-[36px]"
          >
            {refreshing ? 'Refreshing...' : '↻ Refresh Metadata'}
          </button>
          <button
            onClick={() => setShowDeleteModal(true)}
            className="text-sm text-red-400 hover:text-red-300 px-2 min-h-[36px]"
          >
            Delete
          </button>
          <span className="text-xs text-gray-500">
            {detail.files_with_subtitles.length} file{detail.files_with_subtitles.length !== 1 ? 's' : ''} · {formatFileSize(totalSize)}
          </span>
        </div>
      </div>

      {/* Tab navigation */}
      <div className="flex gap-6 border-b border-gray-800 mb-6">
        {tabs.map(tab => (
          <button
            key={tab.key}
            onClick={() => setActiveTab(tab.key)}
            className={`pb-3 text-sm font-medium transition-colors ${
              activeTab === tab.key
                ? 'border-b-2 border-indigo-400 text-indigo-400'
                : 'text-gray-400 hover:text-gray-200'
            }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Overview Tab */}
      {activeTab === 'overview' && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Poster */}
          <div>
            {posterImage ? (
              <img
                src={posterImage.url}
                alt={media.title}
                className="w-full max-w-xs rounded-lg shadow-lg"
              />
            ) : (
              <div className="w-full max-w-xs aspect-[2/3] bg-gray-800 rounded-lg flex items-center justify-center">
                <span className="text-4xl text-gray-500 font-bold">
                  {media.title.charAt(0).toUpperCase()}
                </span>
              </div>
            )}
          </div>

          {/* Info */}
          <div className="lg:col-span-2 space-y-4">
            <div className="flex items-center gap-3">
              <h1 className="text-3xl font-bold text-white">{media.title}</h1>
              {media.year && (
                <span className="px-2 py-0.5 rounded text-sm bg-gray-800 text-gray-300">{media.year}</span>
              )}
            </div>

            {media.original_title && media.original_title !== media.title && (
              <p className="text-sm text-gray-500">{media.original_title}</p>
            )}

            <div className="flex items-center gap-3">
              <StatusBadge status={media.status} />
              <span className={`text-xs px-2 py-0.5 rounded ${media.monitored ? 'bg-indigo-900/30 text-indigo-400' : 'bg-gray-800 text-gray-500'}`}>
                {media.monitored ? 'Monitored' : 'Not Monitored'}
              </span>
            </div>

            {tmdbRating != null && (
              <p className="text-sm text-gray-300">
                ⭐ {tmdbRating.toFixed(1)} / 10
              </p>
            )}

            {genres.length > 0 && (
              <div className="flex flex-wrap gap-2">
                {genres.map(g => (
                  <span key={g} className="px-2 py-0.5 rounded text-xs bg-gray-800 text-gray-400">{g}</span>
                ))}
              </div>
            )}

            <div className="text-sm text-gray-400">
              <span className="font-medium text-gray-300">Quality Profile:</span>{' '}
              {detail.quality_profile?.name ?? <span className="text-gray-500">None configured</span>}
            </div>

            {(media.current_quality || media.desired_quality) && (
              <div className="flex gap-4 text-sm">
                {media.current_quality && (
                  <span className="text-gray-400">
                    Current: <span className="text-gray-200">{media.current_quality.resolution ?? 'Unknown'}</span>
                  </span>
                )}
                {media.desired_quality && (
                  <span className="text-gray-400">
                    Desired: <span className="text-gray-200">{media.desired_quality.resolution ?? 'Unknown'}</span>
                  </span>
                )}
              </div>
            )}

            {media.overview && (
              <div className="mt-4">
                <p className="text-gray-300 leading-relaxed">{media.overview}</p>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Search Tab */}
      {activeTab === 'search' && (
        <div>
          <div className="flex items-center justify-between mb-4">
            <p className="text-sm text-gray-400">
              Searching indexers for "<span className="text-gray-200">{media.title}</span>"
            </p>
            {searchResults.length > 0 && (
              <p className="text-xs text-gray-500">{searchResults.length} result{searchResults.length !== 1 ? 's' : ''}</p>
            )}
          </div>
          {searchError ? (
            <ErrorBanner error={searchError} onRetry={() => setActiveTab('search')} />
          ) : (
            <ReleaseSearchResults
              results={searchResults}
              mediaId={Number(id)}
              mediaType={media.media_type}
              loading={searchLoading}
            />
          )}
        </div>
      )}

      {/* Files Tab */}
      {activeTab === 'files' && (
        detail.files_with_subtitles.length === 0 ? (
          <div className="text-gray-500 text-center py-20 text-sm">No imported files yet</div>
        ) : (
          <div>
            <div className="flex justify-end mb-3">
              <button
                onClick={extractSubs}
                disabled={extracting}
                className="bg-gray-700 hover:bg-gray-600 disabled:opacity-50 px-4 py-2 rounded text-sm font-semibold min-h-[36px]"
              >
                {extracting ? 'Extracting...' : 'Extract All Subtitles'}
              </button>
            </div>
            <div className="bg-gray-900 border border-gray-800 rounded-lg overflow-hidden">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-gray-800">
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-400 uppercase">File Name</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-400 uppercase w-28">Quality</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-400 uppercase w-24">Size</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-400 uppercase w-24">Source</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-400 uppercase w-24">Codec</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-400 uppercase">Subtitles</th>
                  </tr>
                </thead>
                <tbody>
                  {detail.files_with_subtitles.map(file => (
                    <tr key={file.id} className="border-b border-gray-800/50 hover:bg-gray-800/30">
                      <td className="px-4 py-3 text-sm text-gray-200 max-w-md truncate">{file.file_name}</td>
                      <td className="px-4 py-3 text-sm text-gray-400">
                        {file.quality?.resolution ?? file.resolution ?? 'Unknown'}
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-400">{formatFileSize(file.file_size)}</td>
                      <td className="px-4 py-3 text-sm text-gray-400 capitalize">{file.source ?? '—'}</td>
                      <td className="px-4 py-3 text-sm text-gray-400">{file.codec ?? '—'}</td>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          {file.subtitles && file.subtitles.length > 0 ? (
                            <div className="flex flex-wrap gap-1">
                              {file.subtitles.map((sub, idx) => (
                                <span key={idx} className="bg-gray-700 rounded px-2 py-0.5 text-xs text-gray-300 flex items-center gap-1">
                                  {sub.language_code.toUpperCase()}
                                  {sub.hi && <span className="text-yellow-400">SDH</span>}
                                  {sub.forced && <span className="text-blue-400">F</span>}
                                  <span className="text-gray-500 text-[10px]">{sub.source === 'extracted' ? 'EX' : 'DL'}</span>
                                </span>
                              ))}
                            </div>
                          ) : (
                            <span className="text-gray-600 text-xs">None</span>
                          )}
                          <button
                            onClick={() => searchSubtitles(file)}
                            className="text-xs text-indigo-400 hover:text-indigo-300 ml-1 whitespace-nowrap"
                          >
                            Search
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            {subtitleSearchFile && (
              <div className="mt-4 bg-gray-900 border border-gray-800 rounded-lg p-4">
                <div className="flex items-center justify-between mb-3">
                  <h4 className="text-sm font-semibold text-gray-200">
                    Subtitles for &ldquo;{subtitleSearchFile.file_name}&rdquo;
                  </h4>
                  <button
                    onClick={() => { setSubtitleSearchFile(null); setSubtitleResults([]) }}
                    className="text-gray-500 hover:text-gray-300 text-sm"
                  >
                    Close
                  </button>
                </div>
                {subtitleSearchLoading ? (
                  <div className="animate-pulse space-y-2">
                    <div className="h-8 bg-gray-800 rounded" />
                    <div className="h-8 bg-gray-800 rounded" />
                  </div>
                ) : subtitleResults.length === 0 ? (
                  <div className="text-gray-500 text-sm text-center py-8">No subtitles found</div>
                ) : (
                  <table className="w-full">
                    <thead>
                      <tr className="border-b border-gray-800">
                        <th className="text-left px-3 py-2 text-xs font-semibold text-gray-400 uppercase">Language</th>
                        <th className="text-left px-3 py-2 text-xs font-semibold text-gray-400 uppercase">Release</th>
                        <th className="text-left px-3 py-2 text-xs font-semibold text-gray-400 uppercase w-20">Downloads</th>
                        <th className="text-left px-3 py-2 text-xs font-semibold text-gray-400 uppercase w-24">Source</th>
                        <th className="text-left px-3 py-2 text-xs font-semibold text-gray-400 uppercase w-20">Action</th>
                      </tr>
                    </thead>
                    <tbody>
                      {subtitleResults.map(result => {
                        const isDownloading = subtitleDownloading.has(result.id)
                        return (
                          <tr key={result.id} className="border-b border-gray-800/50 hover:bg-gray-800/30">
                            <td className="px-3 py-2 text-sm text-gray-200">
                              {result.language}
                              {result.hi && <span className="text-yellow-400 ml-1 text-xs">SDH</span>}
                              {result.forced && <span className="text-blue-400 ml-1 text-xs">Forced</span>}
                            </td>
                            <td className="px-3 py-2 text-sm text-gray-400 max-w-xs truncate" title={result.release_name}>
                              {result.release_name || '—'}
                            </td>
                            <td className="px-3 py-2 text-sm text-gray-400">{result.download_count}</td>
                            <td className="px-3 py-2 text-sm text-gray-400">{result.provider}</td>
                            <td className="px-3 py-2">
                              <button
                                onClick={() => downloadSub(result)}
                                disabled={isDownloading}
                                className="px-3 py-1 text-xs font-semibold rounded bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50 disabled:cursor-not-allowed"
                              >
                                {isDownloading ? '...' : 'Download'}
                              </button>
                            </td>
                          </tr>
                        )
                      })}
                    </tbody>
                  </table>
                )}
              </div>
            )}
          </div>
        )
      )}

      {/* Episodes Tab */}
      {activeTab === 'episodes' && isSeries && (
        Object.keys(seasons).length === 0 ? (
          <div className="text-gray-500 text-center py-20 text-sm">No episode information available</div>
        ) : (
          <div className="space-y-6">
            {Object.keys(seasons)
              .map(Number)
              .sort((a, b) => a - b)
              .map(seasonNum => (
                <div key={seasonNum}>
                  <h3 className="text-lg font-semibold text-gray-200 mb-3">Season {seasonNum}</h3>
                  <div className="bg-gray-900 border border-gray-800 rounded-lg overflow-hidden">
                    <table className="w-full">
                      <thead>
                        <tr className="border-b border-gray-800">
                          <th className="text-left px-4 py-3 text-xs font-semibold text-gray-400 uppercase w-16">#</th>
                          <th className="text-left px-4 py-3 text-xs font-semibold text-gray-400 uppercase">Title</th>
                          <th className="text-left px-4 py-3 text-xs font-semibold text-gray-400 uppercase w-28">Status</th>
                          <th className="text-center px-4 py-3 text-xs font-semibold text-gray-400 uppercase w-16">Monitor</th>
                          <th className="text-center px-4 py-3 text-xs font-semibold text-gray-400 uppercase w-16">File</th>
                          <th className="text-left px-4 py-3 text-xs font-semibold text-gray-400 uppercase w-28">Quality</th>
                        </tr>
                      </thead>
                      <tbody>
                        {seasons[seasonNum].map(ep => (
                          <tr key={ep.media_id} className="border-b border-gray-800/50 hover:bg-gray-800/30">
                            <td className="px-4 py-3 text-sm text-gray-400">{ep.episode}</td>
                            <td className="px-4 py-3 text-sm text-gray-200">{ep.title}</td>
                            <td className="px-4 py-3">
                              <StatusBadge status={ep.status} />
                            </td>
                            <td className="px-4 py-3 text-center">
                              {ep.monitored ? (
                                <span className="text-green-400">✓</span>
                              ) : (
                                <span className="text-gray-600">✗</span>
                              )}
                            </td>
                            <td className="px-4 py-3 text-center">
                              {ep.has_file ? (
                                <span className="text-green-400">✓</span>
                              ) : (
                                <span className="text-gray-600">—</span>
                              )}
                            </td>
                            <td className="px-4 py-3 text-sm text-gray-400">
                              {ep.quality?.resolution ?? '—'}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              ))}
          </div>
        )
      )}

      {/* History Tab */}
      {activeTab === 'history' && (
        detail.history.length === 0 ? (
          <div className="text-gray-500 text-center py-20 text-sm">No history recorded for this item</div>
        ) : (
          <div className="space-y-0">
            {detail.history.map(event => {
              const badge = eventTypeBadge(event.event_type)
              return (
                <div
                  key={event.id}
                  className="flex gap-4 py-3 border-l-2 border-gray-800 pl-4 ml-2 hover:border-gray-600 transition-colors"
                >
                  <div className="flex-shrink-0">
                    <span className={`inline-block px-2 py-0.5 rounded text-xs font-semibold text-white ${badge.className}`}>
                      {badge.label}
                    </span>
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm text-gray-200 truncate">{event.title}</p>
                    {event.description && (
                      <p className="text-xs text-gray-500 mt-0.5">{event.description}</p>
                    )}
                  </div>
                  <div className="flex-shrink-0 text-xs text-gray-500">
                    {formatTimeAgo(event.created_at)}
                  </div>
                </div>
              )
            })}
          </div>
        )
      )}

      <ConfirmModal
        open={showDeleteModal}
        title="Delete Media"
        message={`Are you sure you want to delete "${media.title}"? This will remove the media item and its associated files from the library. Files on disk will not be deleted.`}
        confirmLabel="Delete"
        destructive
        onConfirm={handleDeleteMedia}
        onCancel={() => setShowDeleteModal(false)}
      />
    </div>
  )
}
