import { useState, useEffect } from 'react'
import { useBreadcrumb } from '../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../config/breadcrumbConfig'
import { Bell, BellOff, Filter, Loader, AlertCircle, Play, Eye, UserPlus, Trash2, X, RotateCcw, CheckCircle, Trash, BellRing, CalendarClock } from 'lucide-react'
import { api } from '../lib/api'
import { formatRelativeTime, formatPlatformName } from '../lib/utils'
import { useSwipeGestures } from '../lib/useSwipeGestures'
import EnhancedLightbox from '../components/EnhancedLightbox'
import { FilterBar } from '../components/FilterPopover'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { notificationManager } from '../lib/notificationManager'
import { invalidateAllFileCaches } from '../lib/cacheInvalidation'

interface MediaFile {
  file_path: string
  filename: string
  media_type: 'image' | 'video'
  file_size?: number
  width?: number
  height?: number
  platform?: string
  source?: string
  download_date?: string
  added_date?: string
  file_token?: string
}

interface Notification {
  id: number
  platform: string
  source: string
  content_type: string
  message: string
  title: string
  priority: number
  download_count: number
  sent_at: string
  status: 'sent' | 'failed'
  metadata: {
    image_path?: string
    media_files?: MediaFile[]
    [key: string]: any
  }
}

interface NotificationStats {
  total_sent: number
  total_failed: number
  by_platform: Record<string, number>
  recent_24h: number
  sources: string[]
}

type FileStatus = 'media' | 'review' | 'recycle' | 'deleted' | 'missing'

import LazyThumbnail from '../components/LazyThumbnail'

export default function Notifications() {
  useBreadcrumb(breadcrumbConfig['/notifications'])
  const queryClient = useQueryClient()
  const [notifications, setNotifications] = useState<Notification[]>([])
  const [stats, setStats] = useState<NotificationStats | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [filterPlatform, setFilterPlatform] = useState<string>('')
  const [filterSource, setFilterSource] = useState<string>('')
  const [searchQuery, setSearchQuery] = useState<string>('')
  const [lightboxItems, setLightboxItems] = useState<MediaFile[]>([])
  const [lightboxIndex, setLightboxIndex] = useState<number>(0)
  const [actioningFile, setActioningFile] = useState<string | null>(null)
  const [showAddModal, setShowAddModal] = useState(false)
  const [addPersonName, setAddPersonName] = useState('')
  const [fileStatuses, setFileStatuses] = useState<Record<string, { status: FileStatus; current_path?: string; recycle_id?: string }>>({})

  // Date edit modal state
  const [showDateModal, setShowDateModal] = useState(false)
  const [editingItemId, setEditingItemId] = useState<number | null>(null)
  const [newDate, setNewDate] = useState('')
  const [updateFileTimestamps, setUpdateFileTimestamps] = useState(true)

  // Mutations
  const batchDeleteMutation = useMutation({
    mutationFn: (filePaths: string[]) => api.batchDeleteMedia(filePaths),
    onSuccess: () => {
      invalidateAllFileCaches(queryClient)
      setActioningFile(null)
      setLightboxItems([]) // Close lightbox
      loadData() // Reload notifications
      api.triggerImmichScan().catch(() => {})
    },
    onError: () => {
      setActioningFile(null)
      notificationManager.error('Delete Failed', 'Failed to delete file', '❌')
    },
  })

  const moveToReviewMutation = useMutation({
    mutationFn: (filePaths: string[]) => api.moveToReview(filePaths),
    onSuccess: (data) => {
      invalidateAllFileCaches(queryClient)
      setActioningFile(null)
      setLightboxItems([]) // Close lightbox
      loadData() // Reload notifications
      notificationManager.success('Moved to Review', `${data.moved_count} item${data.moved_count !== 1 ? 's' : ''} moved to review queue`, '👁️')
      api.triggerImmichScan().catch(() => {})
    },
    onError: () => {
      setActioningFile(null)
      notificationManager.error('Move Failed', 'Failed to move to review', '❌')
    },
  })

  const addFaceReferenceMutation = useMutation({
    mutationFn: (file_path: string) => api.addFaceReference(file_path, undefined, true),
    onSuccess: (data) => {
      setLightboxItems([]) // Close lightbox
      notificationManager.info('Processing', data.message, '⏳')
    },
    onError: (error: any) => {
      const errorMessage = error?.response?.data?.detail || error?.message || 'Failed to add face reference'
      notificationManager.error('Add Reference Failed', errorMessage, '❌')
    },
  })

  const addReferenceMutation = useMutation({
    mutationFn: ({ filePath, personName }: { filePath: string; personName: string }) =>
      api.addFaceReference(filePath, personName, false),
    onSuccess: (data) => {
      invalidateAllFileCaches(queryClient)
      setShowAddModal(false)
      setActioningFile(null)
      setLightboxItems([]) // Close lightbox
      setAddPersonName('')
      notificationManager.success('Face Reference Added', `Added as reference for ${data.person_name}`, '✅')
      api.triggerImmichScan().catch(() => {})
    },
    onError: (error: any) => {
      setActioningFile(null)
      const errorMessage = error?.response?.data?.detail || error?.message || 'Failed to add reference face'
      notificationManager.error('Add Reference Failed', errorMessage, '❌')
    },
  })

  const restoreMutation = useMutation({
    mutationFn: (recycleId: string) => api.post('/recycle/restore', { recycle_id: recycleId }),
    onSuccess: () => {
      invalidateAllFileCaches(queryClient)
      setActioningFile(null)
      setLightboxItems([]) // Close lightbox
      loadData() // Reload notifications
      notificationManager.success('Restored', 'File restored from recycle bin', '✅')
      api.triggerImmichScan().catch(() => {})
    },
    onError: () => {
      setActioningFile(null)
      notificationManager.error('Restore Failed', 'Failed to restore file', '❌')
    },
  })

  const permanentDeleteMutation = useMutation({
    mutationFn: (recycleId: string) => api.delete(`/recycle/delete/${recycleId}`),
    onSuccess: () => {
      invalidateAllFileCaches(queryClient)
      setActioningFile(null)
      setLightboxItems([]) // Close lightbox
      loadData() // Reload notifications
      notificationManager.success('Deleted', 'File permanently deleted', '🗑️')
    },
    onError: () => {
      setActioningFile(null)
      notificationManager.error('Delete Failed', 'Failed to permanently delete file', '❌')
    },
  })

  const reviewKeepMutation = useMutation({
    mutationFn: (filePath: string) => api.reviewKeep(filePath, ''),
    onSuccess: () => {
      invalidateAllFileCaches(queryClient)
      setActioningFile(null)
      setLightboxItems([]) // Close lightbox
      loadData() // Reload notifications
      notificationManager.success('Kept', 'File moved to media library', '✅')
      api.triggerImmichScan().catch(() => {})
    },
    onError: () => {
      setActioningFile(null)
      notificationManager.error('Keep Failed', 'Failed to keep file', '❌')
    },
  })

  const reviewDeleteMutation = useMutation({
    mutationFn: (filePath: string) => api.reviewDelete(filePath),
    onSuccess: () => {
      invalidateAllFileCaches(queryClient)
      setActioningFile(null)
      setLightboxItems([]) // Close lightbox
      loadData() // Reload notifications
      notificationManager.success('Deleted', 'File moved to recycle bin', '🗑️')
    },
    onError: () => {
      setActioningFile(null)
      notificationManager.error('Delete Failed', 'Failed to delete file', '❌')
    },
  })

  const updateDateMutation = useMutation({
    mutationFn: ({ ids, newDate, updateFile }: { ids: number[]; newDate: string; updateFile: boolean }) =>
      api.updateMediaDate(ids, newDate, updateFile, 'post_date'),
    onSuccess: (data) => {
      invalidateAllFileCaches(queryClient)
      setShowDateModal(false)
      setNewDate('')
      setEditingItemId(null)
      notificationManager.success(
        'Date Updated',
        `${data.success_count} file${data.success_count !== 1 ? 's' : ''} updated successfully`,
        '📅'
      )
    },
    onError: () => {
      notificationManager.error('Date Update Failed', 'Failed to update file date', '❌')
    },
  })

  const deleteNotificationMutation = useMutation({
    mutationFn: (notificationId: number) => api.delete(`/notifications/${notificationId}`),
    onSuccess: () => {
      loadData()
      notificationManager.success('Deleted', 'Notification removed from history', '🗑️')
    },
    onError: () => {
      notificationManager.error('Delete Failed', 'Failed to delete notification', '❌')
    },
  })

  const handleDeleteNotification = (notificationId: number) => {
    if (confirm('Delete this notification from history?')) {
      deleteNotificationMutation.mutate(notificationId)
    }
  }

  // Handlers
  const handleSingleMoveToReview = (filePath: string) => {
    if (confirm('Move this item to review queue?')) {
      setActioningFile(filePath)
      moveToReviewMutation.mutate([filePath])
    }
  }

  const handleAddReference = (media: MediaFile) => {
    setActioningFile(media.file_path)
    setShowAddModal(true)
  }

  const handleDelete = (media: MediaFile) => {
    if (confirm(`Delete "${media.filename}"?`)) {
      setActioningFile(media.file_path)
      batchDeleteMutation.mutate([media.file_path])
    }
  }

  const confirmAddReference = () => {
    if (!addPersonName.trim() || !actioningFile) return
    addReferenceMutation.mutate({ filePath: actioningFile, personName: addPersonName })
  }

  // Date editing handlers
  const handleSingleChangeDate = (media: any) => {
    setEditingItemId(media.id)
    // Pre-fill with current post_date if available
    if (media.post_date) {
      const date = new Date(media.post_date)
      const localDateTime = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
        .toISOString()
        .slice(0, 16)
      setNewDate(localDateTime)
    } else {
      setNewDate('')
    }
    setShowDateModal(true)
  }

  const confirmDateChange = () => {
    if (!newDate || !editingItemId) return
    const isoDate = new Date(newDate).toISOString()
    updateDateMutation.mutate({ ids: [editingItemId], newDate: isoDate, updateFile: updateFileTimestamps })
  }

  const handleRestore = (media: MediaFile) => {
    const status = fileStatuses[media.file_path]
    if (status?.recycle_id) {
      if (confirm('Restore this file from recycle bin?')) {
        setActioningFile(media.file_path)
        restoreMutation.mutate(status.recycle_id)
      }
    }
  }

  const handlePermanentDelete = (media: MediaFile) => {
    const status = fileStatuses[media.file_path]
    if (status?.recycle_id) {
      if (confirm('Permanently delete this file? This cannot be undone.')) {
        setActioningFile(media.file_path)
        permanentDeleteMutation.mutate(status.recycle_id)
      }
    }
  }

  const handleReviewKeep = (media: MediaFile) => {
    if (confirm('Keep this file and move to media library?')) {
      setActioningFile(media.file_path)
      reviewKeepMutation.mutate(media.file_path)
    }
  }

  const handleReviewDelete = (media: MediaFile) => {
    if (confirm('Delete this file (move to recycle bin)?')) {
      setActioningFile(media.file_path)
      reviewDeleteMutation.mutate(media.file_path)
    }
  }

  // Helper to get file status
  const getFileStatus = (filePath: string): FileStatus => {
    return fileStatuses[filePath]?.status || 'media'
  }

  // Helper to get status badge
  const getStatusBadge = (status: FileStatus) => {
    switch (status) {
      case 'review':
        return (
          <div className="absolute top-2 left-2 bg-orange-500 text-white px-2 py-0.5 rounded text-xs font-medium">
            In Review
          </div>
        )
      case 'recycle':
        return (
          <div className="absolute top-2 left-2 bg-red-500 text-white px-2 py-0.5 rounded text-xs font-medium">
            Recycle Bin
          </div>
        )
      default:
        return null
    }
  }

  // Helper to get thumbnail URL based on file status
  const getThumbnailUrl = (media: MediaFile) => {
    const statusInfo = fileStatuses[media.file_path]
    const status = statusInfo?.status || 'media'

    if (status === 'recycle' && statusInfo?.recycle_id) {
      // Use recycle bin thumbnail endpoint - auth via httpOnly cookie
      const mediaType = media.media_type === 'video' ? 'video' : 'image'
      return `/api/recycle/file/${statusInfo.recycle_id}?thumbnail=true&type=${mediaType}`
    }

    // Use regular thumbnail endpoint with current_path if file was moved
    return api.getMediaThumbnailUrl(statusInfo?.current_path || media.file_path, media.media_type, media.file_token)
  }

  // Helper to get preview URL based on file status
  const getPreviewUrl = (media: MediaFile) => {
    const statusInfo = fileStatuses[media.file_path]
    const status = statusInfo?.status || 'media'

    if (status === 'recycle' && statusInfo?.recycle_id) {
      // Use recycle bin preview endpoint - auth via httpOnly cookie
      return `/api/recycle/file/${statusInfo.recycle_id}`
    }

    // Use regular preview endpoint with current_path if file was moved
    return api.getMediaPreviewUrl(statusInfo?.current_path || media.file_path, media.file_token)
  }

  const openLightbox = async (mediaFiles: MediaFile[], index: number, notification: Notification) => {
    // Filter out deleted/missing files
    const availableFiles = mediaFiles.filter(file => {
      const status = getFileStatus(file.file_path)
      return status !== 'deleted' && status !== 'missing'
    })

    if (availableFiles.length === 0) {
      notificationManager.info('No Available Files', 'All files in this notification have been deleted', 'ℹ️')
      return
    }

    // Adjust index if files were filtered
    const adjustedIndex = Math.min(index, availableFiles.length - 1)

    // Enrich media files with metadata from notification
    const enrichedFiles = await Promise.all(
      availableFiles.map(async (file) => {
        const statusInfo = fileStatuses[file.file_path]
        const status = statusInfo?.status || 'media'

        try {
          // For recycle bin items, use the recycle metadata endpoint
          if (status === 'recycle' && statusInfo?.recycle_id) {
            const response = await api.get(`/recycle/metadata/${statusInfo.recycle_id}`) as any
            if (response) {
              return {
                ...file,
                width: response.width,
                height: response.height,
                file_size: response.file_size || file.file_size,
                duration: response.duration,
                platform: response.platform || notification.platform,
                source: response.source || notification.source,
                download_date: notification.sent_at
              }
            }
          } else {
            // For regular/review items, use media metadata endpoint
            const currentPath = statusInfo?.current_path || file.file_path
            const metadataUrl = file.file_token ? `/media/metadata?t=${encodeURIComponent(file.file_token)}` : `/media/metadata?file_path=${encodeURIComponent(currentPath)}`
            const response = await api.get(metadataUrl) as any
            if (response) {
              return {
                ...file,
                width: response.width,
                height: response.height,
                file_size: response.file_size || file.file_size,
                duration: response.duration,
                platform: response.platform || notification.platform,
                source: response.source || notification.source,
                download_date: notification.sent_at
              }
            }
          }
        } catch (error) {
          console.log('Could not fetch full metadata for', file.filename)
        }
        // Fallback: use notification metadata
        return {
          ...file,
          platform: notification.platform,
          source: notification.source,
          download_date: notification.sent_at
        }
      })
    )
    setLightboxItems(enrichedFiles)
    setLightboxIndex(adjustedIndex)
  }

  useEffect(() => {
    loadData()
  }, [filterPlatform, filterSource])

  const loadData = async () => {
    try {
      setLoading(true)

      // Load notifications with filters
      const params: any = { limit: 100 }
      if (filterPlatform) params.platform = filterPlatform
      if (filterSource) params.source = filterSource

      const query = new URLSearchParams(params).toString()
      const notifResponse = await api.get<{
        notifications: Notification[]
        total: number
      }>(`/notifications?${query}`)

      // Load stats
      const statsResponse = await api.get<NotificationStats>('/notifications/stats')

      setNotifications(notifResponse.notifications || [])
      setStats(statsResponse)

      // Collect all file paths from notifications to check their status
      const allFilePaths: string[] = []
      for (const notif of notifResponse.notifications || []) {
        if (notif.metadata?.media_files) {
          for (const media of notif.metadata.media_files) {
            allFilePaths.push(media.file_path)
          }
        }
      }

      // Check file statuses in batches
      if (allFilePaths.length > 0) {
        try {
          const statusResponse = await api.checkFileStatuses(allFilePaths)
          setFileStatuses(statusResponse.file_statuses || {})
        } catch (e) {
          console.error('Failed to check file statuses:', e)
          // Don't fail the whole load if status check fails
        }
      }

      setError(null)
    } catch (error) {
      console.error('Failed to load notifications:', error)
      setError('Failed to load notifications')
    } finally {
      setLoading(false)
    }
  }

  const getStatusColor = (status: string) => {
    return status === 'sent'
      ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400'
      : 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400'
  }

  const getPriorityColor = (priority: number) => {
    if (priority >= 1) return 'text-red-600 dark:text-red-400'
    if (priority === 0) return 'text-blue-600 dark:text-blue-400'
    return 'text-slate-500 dark:text-slate-400'
  }

  // Enable swipe gestures when lightbox is open
  useSwipeGestures({
    onSwipeLeft: undefined,
    onSwipeRight: undefined,
    onSwipeDown: lightboxItems.length > 0 ? () => setLightboxItems([]) : undefined,
  })

  if (loading && !stats) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <Loader className="w-8 h-8 animate-spin text-blue-600 dark:text-blue-400" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
            <BellRing className="w-8 h-8 text-amber-500" />
            Notifications History
          </h1>
          <p className="text-slate-600 dark:text-slate-400 mt-1">
            View and manage push notification history
          </p>
        </div>
        <button
          onClick={loadData}
          className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors btn-hover-lift"
        >
          Refresh
        </button>
      </div>

      {/* Stats Cards */}
      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="card-glass-hover rounded-xl p-4 border stat-card-green shadow-green-glow">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Total Sent</p>
                <p className="text-2xl font-bold text-emerald-600 dark:text-emerald-400">{stats.total_sent}</p>
              </div>
              <div className="p-3 rounded-xl bg-emerald-500/20">
                <Bell className="w-6 h-6 text-emerald-600 dark:text-emerald-400" />
              </div>
            </div>
          </div>

          <div className="card-glass-hover rounded-xl p-4 border stat-card-red shadow-red-glow">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Failed</p>
                <p className="text-2xl font-bold text-red-600 dark:text-red-400">{stats.total_failed}</p>
              </div>
              <div className="p-3 rounded-xl bg-red-500/20">
                <BellOff className="w-6 h-6 text-red-600 dark:text-red-400" />
              </div>
            </div>
          </div>

          <div className="card-glass-hover rounded-xl p-4 border stat-card-blue shadow-blue-glow">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Last 24h</p>
                <p className="text-2xl font-bold text-blue-600 dark:text-blue-400">{stats.recent_24h}</p>
              </div>
              <div className="p-3 rounded-xl bg-blue-500/20">
                <Bell className="w-6 h-6 text-blue-600 dark:text-blue-400" />
              </div>
            </div>
          </div>

          <div className="card-glass-hover rounded-xl p-4 border stat-card-purple shadow-purple-glow">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Platforms</p>
                <p className="text-2xl font-bold text-violet-600 dark:text-violet-400">
                  {Object.keys(stats.by_platform).length}
                </p>
              </div>
              <div className="p-3 rounded-xl bg-violet-500/20">
                <Filter className="w-6 h-6 text-violet-600 dark:text-violet-400" />
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Filters */}
      <div className="card-glass-hover rounded-xl p-4 relative z-30">
        <FilterBar
          searchValue={searchQuery}
          onSearchChange={setSearchQuery}
          searchPlaceholder="Search notifications..."
          filterSections={[
            {
              id: 'platform',
              label: 'Platform',
              type: 'select',
              options: [
                { value: '', label: 'All Platforms' },
                ...(stats ? Object.keys(stats.by_platform).sort().map(platform => ({
                  value: platform,
                  label: formatPlatformName(platform)
                })) : [])
              ],
              value: filterPlatform,
              onChange: (v) => setFilterPlatform(v as string)
            },
            {
              id: 'source',
              label: 'Source',
              type: 'select',
              options: [
                { value: '', label: 'All Sources' },
                ...(stats?.sources?.map(source => ({
                  value: source,
                  label: source
                })) || [])
              ],
              value: filterSource,
              onChange: (v) => setFilterSource(v as string)
            }
          ]}
          activeFilters={[
            ...(filterPlatform ? [{
              id: 'platform',
              label: 'Platform',
              value: filterPlatform,
              displayValue: formatPlatformName(filterPlatform),
              onRemove: () => setFilterPlatform('')
            }] : []),
            ...(filterSource ? [{
              id: 'source',
              label: 'Source',
              value: filterSource,
              displayValue: filterSource,
              onRemove: () => setFilterSource('')
            }] : [])
          ]}
          onClearAll={() => {
            setFilterPlatform('')
            setFilterSource('')
            setSearchQuery('')
          }}
          totalCount={notifications.filter(n => {
            if (!searchQuery) return true
            const query = searchQuery.toLowerCase()
            return n.title.toLowerCase().includes(query) ||
                   n.message.toLowerCase().includes(query) ||
                   n.source.toLowerCase().includes(query)
          }).length}
          countLabel="notifications"
        />
      </div>

      {/* Error */}
      {error && (
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
          <div className="flex items-center space-x-2">
            <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400" />
            <p className="text-red-700 dark:text-red-400">{error}</p>
          </div>
        </div>
      )}

      {/* Notifications List */}
      <div className="space-y-3">
        {loading ? (
          <div className="flex items-center justify-center py-12">
            <Loader className="w-8 h-8 animate-spin text-blue-600 dark:text-blue-400" />
          </div>
        ) : notifications.length === 0 ? (
          <div className="card-glass-hover rounded-xl p-12 text-center">
            <Bell className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
            <p className="text-muted-foreground">No notifications found</p>
          </div>
        ) : (
          notifications
            .filter(n => {
              if (!searchQuery) return true
              const query = searchQuery.toLowerCase()
              return n.title.toLowerCase().includes(query) ||
                     n.message.toLowerCase().includes(query) ||
                     n.source.toLowerCase().includes(query)
            })
            .map((notification) => {
            // Get media files from metadata
            const mediaFiles = notification.metadata?.media_files || []
            const hasMedia = mediaFiles.length > 0

            return (
            <div
              key={notification.id}
              className="card-glass-hover rounded-xl p-4"
            >
              <div className="flex flex-col gap-4">
                <div className="flex items-start gap-4">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center space-x-3 mb-2">
                      <Bell className={`w-5 h-5 ${getPriorityColor(notification.priority)}`} />
                      <h3 className="font-semibold text-slate-900 dark:text-slate-100">
                        {notification.title}
                      </h3>
                      <span
                        className={`px-2 py-0.5 text-xs font-medium rounded-full ${getStatusColor(
                          notification.status
                        )}`}
                      >
                        {notification.status}
                      </span>
                    </div>

                    <div className="text-sm text-slate-600 dark:text-slate-400 mb-3 whitespace-pre-wrap">
                      {notification.message.replace(/<[^>]*>/g, '').replace(/&lt;/g, '<').replace(/&gt;/g, '>')}
                    </div>

                    <div className="flex flex-wrap gap-3 text-xs text-slate-500 dark:text-slate-400">
                      <span>
                        Platform: <span className="font-medium">{formatPlatformName(notification.platform)}</span>
                      </span>
                      {notification.source && (
                        <span>
                          Source: <span className="font-medium">{notification.source}</span>
                        </span>
                      )}
                      {notification.download_count > 0 && (
                        <span>
                          Count: <span className="font-medium">{notification.download_count}</span>
                        </span>
                      )}
                      <span>
                        Priority: <span className="font-medium">{notification.priority}</span>
                      </span>
                    </div>
                  </div>

                  <div className="flex flex-col items-end gap-2 flex-shrink-0">
                    <div className="text-xs text-slate-500 dark:text-slate-400">
                      {formatRelativeTime(notification.sent_at)}
                    </div>
                    <button
                      onClick={() => handleDeleteNotification(notification.id)}
                      disabled={deleteNotificationMutation.isPending}
                      className="p-1.5 text-slate-400 hover:text-red-500 dark:text-slate-500 dark:hover:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors"
                      title="Delete notification"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>

                {/* Media Thumbnails Grid - Matches Media/Review page sizing */}
                {hasMedia && (() => {
                  // Filter out deleted/missing files
                  const availableMedia = mediaFiles.filter(media => {
                    const status = getFileStatus(media.file_path)
                    return status !== 'deleted' && status !== 'missing'
                  })

                  if (availableMedia.length === 0) return null

                  return (
                    <div className="pt-3 border-t border-slate-200 dark:border-slate-700">
                      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                        {availableMedia.map((media, idx) => {
                          const status = getFileStatus(media.file_path)

                          return (
                            <div
                              key={idx}
                              className={`relative aspect-square cursor-pointer group rounded-lg overflow-hidden border-2 transition-colors ${
                                status === 'review'
                                  ? 'border-orange-400 dark:border-orange-500'
                                  : status === 'recycle'
                                  ? 'border-red-400 dark:border-red-500'
                                  : 'border-slate-200 dark:border-slate-700 hover:border-blue-500'
                              }`}
                              onClick={() => openLightbox(availableMedia, idx, notification)}
                            >
                              <LazyThumbnail
                                src={getThumbnailUrl(media)}
                                alt={media.filename}
                                className="w-full h-full object-cover"
                              />

                              {/* Status Badge */}
                              {getStatusBadge(status)}

                              {/* Video indicator */}
                              {media.media_type === 'video' && (
                                <div className={`absolute ${status === 'review' || status === 'recycle' ? 'top-8' : 'top-2'} right-2`}>
                                  <div className="bg-black/60 rounded-full p-1.5">
                                    <Play className="w-4 h-4 text-white fill-white" />
                                  </div>
                                </div>
                              )}

                              {/* Action buttons overlay - Context-aware based on file status */}
                              <div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex flex-col items-center justify-center space-y-2 p-2">
                                {status === 'media' && (
                                  <>
                                    <button
                                      onClick={(e) => {
                                        e.stopPropagation()
                                        handleSingleMoveToReview(media.file_path)
                                      }}
                                      disabled={actioningFile === media.file_path}
                                      className="w-full px-3 py-2.5 bg-orange-600 text-white rounded-lg hover:bg-orange-700 disabled:opacity-50 flex items-center justify-center space-x-2 text-sm min-h-[44px] transition-colors"
                                    >
                                      <Eye className="w-4 h-4" />
                                      <span>Review</span>
                                    </button>
                                    <button
                                      onClick={(e) => {
                                        e.stopPropagation()
                                        handleAddReference(media)
                                      }}
                                      disabled={actioningFile === media.file_path}
                                      className="w-full px-3 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center space-x-2 text-sm min-h-[44px] transition-colors"
                                    >
                                      <UserPlus className="w-4 h-4" />
                                      <span>Add Reference</span>
                                    </button>
                                    <button
                                      onClick={(e) => {
                                        e.stopPropagation()
                                        handleDelete(media)
                                      }}
                                      disabled={actioningFile === media.file_path}
                                      className="w-full px-3 py-2.5 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 flex items-center justify-center space-x-2 text-sm min-h-[44px] transition-colors"
                                    >
                                      <Trash2 className="w-4 h-4" />
                                      <span>Delete</span>
                                    </button>
                                  </>
                                )}

                                {status === 'review' && (
                                  <>
                                    <button
                                      onClick={(e) => {
                                        e.stopPropagation()
                                        handleReviewKeep(media)
                                      }}
                                      disabled={actioningFile === media.file_path}
                                      className="w-full px-3 py-2.5 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 flex items-center justify-center space-x-2 text-sm min-h-[44px] transition-colors"
                                    >
                                      <CheckCircle className="w-4 h-4" />
                                      <span>Keep</span>
                                    </button>
                                    <button
                                      onClick={(e) => {
                                        e.stopPropagation()
                                        handleReviewDelete(media)
                                      }}
                                      disabled={actioningFile === media.file_path}
                                      className="w-full px-3 py-2.5 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 flex items-center justify-center space-x-2 text-sm min-h-[44px] transition-colors"
                                    >
                                      <Trash2 className="w-4 h-4" />
                                      <span>Delete</span>
                                    </button>
                                  </>
                                )}

                                {status === 'recycle' && (
                                  <>
                                    <button
                                      onClick={(e) => {
                                        e.stopPropagation()
                                        handleRestore(media)
                                      }}
                                      disabled={actioningFile === media.file_path}
                                      className="w-full px-3 py-2.5 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 flex items-center justify-center space-x-2 text-sm min-h-[44px] transition-colors"
                                    >
                                      <RotateCcw className="w-4 h-4" />
                                      <span>Restore</span>
                                    </button>
                                    <button
                                      onClick={(e) => {
                                        e.stopPropagation()
                                        handlePermanentDelete(media)
                                      }}
                                      disabled={actioningFile === media.file_path}
                                      className="w-full px-3 py-2.5 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 flex items-center justify-center space-x-2 text-sm min-h-[44px] transition-colors"
                                    >
                                      <Trash className="w-4 h-4" />
                                      <span>Delete Forever</span>
                                    </button>
                                  </>
                                )}
                              </div>

                              {/* File info overlay */}
                              <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                <p className="text-white text-xs truncate">{media.filename}</p>
                              </div>
                            </div>
                          )
                        })}
                      </div>
                    </div>
                  )
                })()}
              </div>
            </div>
            )
          })
        )}
      </div>

      {/* Enhanced Lightbox */}
      {lightboxItems.length > 0 && (
        <EnhancedLightbox
          items={lightboxItems}
          currentIndex={lightboxIndex}
          onNavigate={setLightboxIndex}
          onClose={() => setLightboxItems([])}
          onDelete={handleDelete}
          onEditDate={handleSingleChangeDate}
          getPreviewUrl={(item: MediaFile) => getPreviewUrl(item)}
          getThumbnailUrl={(item: MediaFile) => getThumbnailUrl(item)}
          isVideo={(item: MediaFile) => item.media_type === 'video'}
          renderActions={(item: MediaFile) => {
            const status = getFileStatus(item.file_path)

            // Media files - show standard actions
            if (status === 'media') {
              return (
                <>
                  <button
                    onClick={() => handleSingleMoveToReview(item.file_path)}
                    disabled={moveToReviewMutation.isPending || actioningFile === item.file_path}
                    className="px-3 py-1.5 md:px-6 md:py-3 bg-orange-600 text-white text-sm md:text-base rounded-lg hover:bg-orange-700 disabled:opacity-50 flex items-center space-x-1.5 md:space-x-2 transition-colors"
                  >
                    <Eye className="w-4 h-4 md:w-5 md:h-5" />
                    <span>{moveToReviewMutation.isPending ? 'Moving...' : 'Move to Review'}</span>
                  </button>
                  <button
                    onClick={() => handleAddReference(item)}
                    disabled={actioningFile === item.file_path}
                    className="px-3 py-1.5 md:px-6 md:py-3 bg-blue-600 text-white text-sm md:text-base rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center space-x-1.5 md:space-x-2 transition-colors"
                  >
                    <UserPlus className="w-4 h-4 md:w-5 md:h-5" />
                    <span>Add Reference</span>
                  </button>
                  <button
                    onClick={() => addFaceReferenceMutation.mutate(item.file_path)}
                    disabled={addFaceReferenceMutation.isPending}
                    className="px-3 py-1.5 md:px-6 md:py-3 bg-purple-600 text-white text-sm md:text-base rounded-lg hover:bg-purple-700 disabled:opacity-50 flex items-center space-x-1.5 md:space-x-2 transition-colors"
                  >
                    <UserPlus className="w-4 h-4 md:w-5 md:h-5" />
                    <span>{addFaceReferenceMutation.isPending ? 'Adding...' : 'Quick Add Face'}</span>
                  </button>
                  <button
                    onClick={() => handleDelete(item)}
                    disabled={actioningFile === item.file_path}
                    className="px-3 py-1.5 md:px-6 md:py-3 bg-red-600 text-white text-sm md:text-base rounded-lg hover:bg-red-700 disabled:opacity-50 flex items-center space-x-1.5 md:space-x-2 transition-colors"
                  >
                    <Trash2 className="w-4 h-4 md:w-5 md:h-5" />
                    <span>Delete</span>
                  </button>
                </>
              )
            }

            // Review files - show keep/delete actions
            if (status === 'review') {
              return (
                <>
                  <div className="px-3 py-1.5 bg-orange-500/80 text-white text-sm rounded-lg">
                    In Review Queue
                  </div>
                  <button
                    onClick={() => handleReviewKeep(item)}
                    disabled={reviewKeepMutation.isPending || actioningFile === item.file_path}
                    className="px-3 py-1.5 md:px-6 md:py-3 bg-green-600 text-white text-sm md:text-base rounded-lg hover:bg-green-700 disabled:opacity-50 flex items-center space-x-1.5 md:space-x-2 transition-colors"
                  >
                    <CheckCircle className="w-4 h-4 md:w-5 md:h-5" />
                    <span>{reviewKeepMutation.isPending ? 'Keeping...' : 'Keep'}</span>
                  </button>
                  <button
                    onClick={() => handleReviewDelete(item)}
                    disabled={reviewDeleteMutation.isPending || actioningFile === item.file_path}
                    className="px-3 py-1.5 md:px-6 md:py-3 bg-red-600 text-white text-sm md:text-base rounded-lg hover:bg-red-700 disabled:opacity-50 flex items-center space-x-1.5 md:space-x-2 transition-colors"
                  >
                    <Trash2 className="w-4 h-4 md:w-5 md:h-5" />
                    <span>{reviewDeleteMutation.isPending ? 'Deleting...' : 'Delete'}</span>
                  </button>
                </>
              )
            }

            // Recycle bin files - show restore/permanent delete actions
            if (status === 'recycle') {
              return (
                <>
                  <div className="px-3 py-1.5 bg-red-500/80 text-white text-sm rounded-lg">
                    In Recycle Bin
                  </div>
                  <button
                    onClick={() => handleRestore(item)}
                    disabled={restoreMutation.isPending || actioningFile === item.file_path}
                    className="px-3 py-1.5 md:px-6 md:py-3 bg-green-600 text-white text-sm md:text-base rounded-lg hover:bg-green-700 disabled:opacity-50 flex items-center space-x-1.5 md:space-x-2 transition-colors"
                  >
                    <RotateCcw className="w-4 h-4 md:w-5 md:h-5" />
                    <span>{restoreMutation.isPending ? 'Restoring...' : 'Restore'}</span>
                  </button>
                  <button
                    onClick={() => handlePermanentDelete(item)}
                    disabled={permanentDeleteMutation.isPending || actioningFile === item.file_path}
                    className="px-3 py-1.5 md:px-6 md:py-3 bg-red-600 text-white text-sm md:text-base rounded-lg hover:bg-red-700 disabled:opacity-50 flex items-center space-x-1.5 md:space-x-2 transition-colors"
                  >
                    <Trash className="w-4 h-4 md:w-5 md:h-5" />
                    <span>{permanentDeleteMutation.isPending ? 'Deleting...' : 'Delete Forever'}</span>
                  </button>
                </>
              )
            }

            // Fallback - shouldn't happen but show basic info
            return (
              <div className="px-3 py-1.5 bg-slate-500/80 text-white text-sm rounded-lg">
                File unavailable
              </div>
            )
          }}
        />
      )}

      {/* Add Reference Modal */}
      {showAddModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-card border border-border rounded-xl p-6 max-w-md w-full shadow-2xl">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-bold text-slate-900 dark:text-slate-100">Add Face Reference</h2>
              <button
                onClick={() => {
                  setShowAddModal(false)
                  setAddPersonName('')
                  setActioningFile(null)
                }}
                className="text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200"
              >
                <X className="w-6 h-6" />
              </button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  Person Name
                </label>
                <input
                  type="text"
                  value={addPersonName}
                  onChange={(e) => setAddPersonName(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter') confirmAddReference()
                  }}
                  placeholder="Enter person name..."
                  className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500"
                  autoFocus
                />
              </div>
              <div className="flex justify-end space-x-2">
                <button
                  onClick={() => {
                    setShowAddModal(false)
                    setAddPersonName('')
                    setActioningFile(null)
                  }}
                  className="px-4 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-100"
                >
                  Cancel
                </button>
                <button
                  onClick={confirmAddReference}
                  disabled={!addPersonName.trim() || addReferenceMutation.isPending}
                  className="px-4 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed min-h-[44px] transition-colors"
                >
                  {addReferenceMutation.isPending ? 'Adding...' : 'Add Reference'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Date Edit Modal */}
      {showDateModal && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-card border border-border rounded-xl p-6 max-w-md w-full shadow-2xl">
            <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4 flex items-center space-x-2">
              <CalendarClock className="w-5 h-5 text-amber-500" />
              <span>Edit Post Date</span>
            </h3>
            <p className="text-sm text-slate-600 dark:text-slate-400 mb-4">
              Change the post date for this file. This will update the database and optionally update file timestamps.
            </p>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  New Date and Time
                </label>
                <input
                  type="datetime-local"
                  value={newDate}
                  onChange={(e) => setNewDate(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-900 text-slate-900 dark:text-slate-100"
                  autoFocus
                />
              </div>
              <div className="flex items-center space-x-2">
                <input
                  type="checkbox"
                  id="updateFileTimestampsNotifications"
                  checked={updateFileTimestamps}
                  onChange={(e) => setUpdateFileTimestamps(e.target.checked)}
                  className="w-4 h-4 text-amber-600 border-slate-300 rounded focus:ring-amber-500"
                />
                <label htmlFor="updateFileTimestampsNotifications" className="text-sm text-slate-700 dark:text-slate-300">
                  Update file timestamps (EXIF/metadata and filesystem)
                </label>
              </div>
            </div>
            <div className="flex justify-end space-x-2 mt-6">
              <button
                onClick={() => {
                  setShowDateModal(false)
                  setNewDate('')
                  setEditingItemId(null)
                }}
                className="px-4 py-2.5 text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg min-h-[44px] transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={confirmDateChange}
                disabled={!newDate || updateDateMutation.isPending}
                className="px-4 py-2.5 bg-amber-600 text-white rounded-lg hover:bg-amber-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-2 min-h-[44px] transition-colors"
              >
                {updateDateMutation.isPending ? (
                  <>
                    <span className="animate-spin">⏳</span>
                    <span>Updating...</span>
                  </>
                ) : (
                  <span>Apply</span>
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
