import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useBreadcrumb } from '../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../config/breadcrumbConfig'
import {
  Tags, FolderSearch, Library, Calendar, Plus, Edit2, Trash2,
  Folder, ExternalLink, Filter, Activity, Download,
  Clock, Image, Video, HardDrive, Camera, MessageCircle,
  Film, Youtube, Tv, Zap, Search, Sparkles, Loader2, Play, Eye, UserPlus, Compass
} from 'lucide-react'
import { api } from '../lib/api'
import { formatBytes, isVideoFile } from '../lib/utils'
import { notificationManager } from '../lib/notificationManager'
import { invalidateAllFileCaches } from '../lib/cacheInvalidation'
import ThrottledImage from '../components/ThrottledImage'
import EnhancedLightbox from '../components/EnhancedLightbox'

// Types
interface SmartFolder {
  id: number
  name: string
  slug: string
  icon: string
  color: string
  description: string | null
  filters: Record<string, any>
  sort_by: string
  sort_order: string
  is_system: boolean
  display_order: number
}

interface TimelineEntry {
  date: string
  file_count: number
  total_size: number
  image_count: number
  video_count: number
}

// Color palette for tags
const TAG_COLORS = [
  '#ef4444', '#f97316', '#f59e0b', '#84cc16', '#22c55e',
  '#14b8a6', '#06b6d4', '#3b82f6', '#6366f1', '#8b5cf6',
  '#a855f7', '#d946ef', '#ec4899', '#f43f5e', '#64748b'
]

// Icon options
const FOLDER_ICONS = [
  'folder', 'clock', 'image', 'video', 'star', 'heart',
  'bookmark', 'tag', 'archive', 'file', 'camera', 'film'
]

export default function Discovery() {
  useBreadcrumb(breadcrumbConfig['/discovery'])
  const queryClient = useQueryClient()
  const navigate = useNavigate()
  const [activeTab, setActiveTab] = useState<'smart-folders' | 'timeline' | 'search' | 'activity'>('search')

  // Search state
  const [searchQuery, setSearchQuery] = useState('')
  const [searchResults, setSearchResults] = useState<any[]>([])
  const [isSearching, setIsSearching] = useState(false)
  const [hasSearched, setHasSearched] = useState(false)
  const [isIndexing, setIsIndexing] = useState(false)
  const [lastEmbeddingCount, setLastEmbeddingCount] = useState<number | null>(null)
  const [stallCount, setStallCount] = useState(0)
  const [lightboxIndex, setLightboxIndex] = useState<number>(-1)

  // Smart Folders state
  const [showFolderModal, setShowFolderModal] = useState(false)
  const [editingFolder, setEditingFolder] = useState<SmartFolder | null>(null)
  const [folderForm, setFolderForm] = useState({
    name: '',
    icon: 'folder',
    color: '#6366f1',
    description: '',
    filters: {} as Record<string, any>
  })

  // Timeline state
  const [timelineGranularity, setTimelineGranularity] = useState<'day' | 'week' | 'month' | 'year'>('month')
  const [timelineYear, setTimelineYear] = useState(new Date().getFullYear())

  // API Queries
  const { data: smartFoldersData, isLoading: foldersLoading } = useQuery({
    queryKey: ['smart-folders'],
    queryFn: async () => {
      const response = await api.get<{ smart_folders: SmartFolder[] }>('/smart-folders')
      return response.smart_folders
    },
    enabled: activeTab === 'smart-folders'
  })

  // Smart folder stats (counts and previews)
  const { data: folderStatsData } = useQuery({
    queryKey: ['smart-folder-stats'],
    queryFn: () => api.getSmartFolderStats(),
    enabled: activeTab === 'smart-folders'
  })

  const { data: timelineData, isLoading: timelineLoading } = useQuery({
    queryKey: ['timeline', timelineGranularity],
    queryFn: async () => {
      const response = await api.get<{ timeline: TimelineEntry[], granularity: string }>(
        `/timeline?granularity=${timelineGranularity}`
      )
      return response.timeline
    },
    enabled: activeTab === 'timeline'
  })

  const { data: heatmapData } = useQuery({
    queryKey: ['timeline-heatmap', timelineYear],
    queryFn: async () => {
      const response = await api.get<{ heatmap: Record<string, number>, year: number }>(
        `/timeline/heatmap?year=${timelineYear}`
      )
      return response.heatmap
    },
    enabled: activeTab === 'timeline'
  })

  // Semantic search stats - poll frequently while on search tab to detect background indexing
  const { data: semanticStats } = useQuery({
    queryKey: ['semantic-stats'],
    queryFn: () => api.getSemanticStats(),
    enabled: activeTab === 'search',
    // Poll every 2s while indexing is detected, otherwise every 10s to detect new indexing
    refetchInterval: isIndexing ? 2000 : 10000,
  })

  // Recent activity
  const { data: activityData, isLoading: activityLoading } = useQuery({
    queryKey: ['recent-activity'],
    queryFn: () => api.getRecentActivity(15),
    enabled: activeTab === 'activity',
    refetchInterval: 30000, // Refresh every 30s
  })

  // Auto-detect indexing (from any source) by watching embedding count changes
  useEffect(() => {
    if (!semanticStats) return

    const currentCount = semanticStats.total_embeddings

    if (lastEmbeddingCount !== null) {
      // Count changed - indexing is happening
      if (currentCount !== lastEmbeddingCount) {
        if (!isIndexing) {
          setIsIndexing(true)
        }
        setStallCount(0)
      } else if (isIndexing) {
        // No change while we think indexing is active - check for stall
        const newStallCount = stallCount + 1
        setStallCount(newStallCount)

        // After 5 polls with no progress, consider it done/stalled
        if (newStallCount >= 5) {
          setIsIndexing(false)
          setStallCount(0)
          // Only show completion notification, not "paused" - that's too noisy
          if (semanticStats.missing_embeddings === 0) {
            notificationManager.success('Indexing Complete', `All ${semanticStats.total_files.toLocaleString()} files indexed`)
          }
        }
      }
    }

    setLastEmbeddingCount(currentCount)
  }, [semanticStats, isIndexing, lastEmbeddingCount, stallCount])

  // Generate embeddings mutation
  const generateEmbeddingsMutation = useMutation({
    mutationFn: (params?: { limit?: number; platform?: string }) => api.generateEmbeddings(params),
    onSuccess: () => {
      setIsIndexing(true)
      setStallCount(0)
      setLastEmbeddingCount(null)
      notificationManager.success('Indexing Started', 'Processing images in the background...')
    },
    onError: () => {
      notificationManager.error('Error', 'Failed to start embedding generation')
    }
  })

  // Perform semantic search
  const performSearch = async () => {
    if (!searchQuery.trim()) return

    setIsSearching(true)
    setHasSearched(true)
    try {
      const response = await api.semanticSearch({ query: searchQuery, limit: 100 })
      setSearchResults(response.results)
    } catch (error) {
      notificationManager.error('Search Failed', 'Could not perform semantic search')
      setSearchResults([])
    } finally {
      setIsSearching(false)
    }
  }

  // Media action mutations
  const moveToReviewMutation = useMutation({
    mutationFn: async (filePath: string) => {
      return api.post('/media/move-to-review', { file_paths: [filePath] })
    },
    onSuccess: (_, filePath) => {
      notificationManager.success('Moved to Review', 'File moved to review queue')
      setSearchResults(prev => prev.filter(r => r.file_path !== filePath))
      invalidateAllFileCaches(queryClient)
    },
    onError: () => {
      notificationManager.error('Error', 'Failed to move file to review')
    }
  })

  const deleteMutation = useMutation({
    mutationFn: async (filePath: string) => {
      return api.batchDeleteMedia([filePath])
    },
    onSuccess: (_, filePath) => {
      // Notification handled by websocket batch_delete_completed in App.tsx
      setSearchResults(prev => prev.filter(r => r.file_path !== filePath))
      if (lightboxIndex >= 0 && searchResults.length <= 1) {
        setLightboxIndex(-1)
      } else if (lightboxIndex >= searchResults.length - 1) {
        setLightboxIndex(Math.max(0, searchResults.length - 2))
      }
      invalidateAllFileCaches(queryClient)
    },
    onError: () => {
      notificationManager.error('Error', 'Failed to delete file')
    }
  })

  const handleMoveToReview = (filePath: string) => {
    moveToReviewMutation.mutate(filePath)
  }

  const handleDelete = (item: any) => {
    if (confirm(`Delete ${item.filename}?`)) {
      deleteMutation.mutate(item.file_path)
    }
  }

  // Mutations
  const createFolderMutation = useMutation({
    mutationFn: async (data: typeof folderForm) => {
      return api.post('/smart-folders', data)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['smart-folders'] })
      setShowFolderModal(false)
      setFolderForm({ name: '', icon: 'folder', color: '#6366f1', description: '', filters: {} })
      notificationManager.success('Smart Folder Created', 'Smart folder has been created')
    },
    onError: () => {
      notificationManager.error('Error', 'Failed to create smart folder')
    }
  })

  const updateFolderMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number, data: Partial<SmartFolder> }) => {
      return api.put(`/smart-folders/${id}`, data)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['smart-folders'] })
      setShowFolderModal(false)
      setEditingFolder(null)
      notificationManager.success('Smart Folder Updated', 'Smart folder has been updated')
    },
    onError: () => {
      notificationManager.error('Error', 'Failed to update smart folder')
    }
  })

  const deleteFolderMutation = useMutation({
    mutationFn: async (id: number) => {
      return api.delete(`/smart-folders/${id}`)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['smart-folders'] })
      notificationManager.success('Smart Folder Deleted', 'Smart folder has been deleted')
    },
    onError: () => {
      notificationManager.error('Error', 'Cannot delete system smart folders')
    }
  })

  // Render Activity Heatmap
  const renderHeatmap = () => {
    if (!heatmapData) return null

    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

    // Get max value for color scaling
    const values = Object.values(heatmapData)
    const maxValue = Math.max(...values, 1)

    // Generate calendar grid
    const startDate = new Date(timelineYear, 0, 1)
    const endDate = new Date(timelineYear, 11, 31)

    const getColorIntensity = (count: number) => {
      if (count === 0) return 'bg-slate-100 dark:bg-slate-800'
      const intensity = Math.min(count / maxValue, 1)
      if (intensity < 0.25) return 'bg-green-200 dark:bg-green-900'
      if (intensity < 0.5) return 'bg-green-400 dark:bg-green-700'
      if (intensity < 0.75) return 'bg-green-500 dark:bg-green-600'
      return 'bg-green-600 dark:bg-green-500'
    }

    // Group by weeks
    const weeks: { date: Date, count: number }[][] = []
    let currentWeek: { date: Date, count: number }[] = []

    // Pad first week
    const firstDayOfWeek = startDate.getDay()
    for (let i = 0; i < firstDayOfWeek; i++) {
      currentWeek.push({ date: new Date(0), count: -1 }) // -1 = empty cell
    }

    for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
      const dateStr = d.toISOString().split('T')[0]
      const count = heatmapData[dateStr] || 0
      currentWeek.push({ date: new Date(d), count })

      if (currentWeek.length === 7) {
        weeks.push(currentWeek)
        currentWeek = []
      }
    }

    // Pad last week
    while (currentWeek.length > 0 && currentWeek.length < 7) {
      currentWeek.push({ date: new Date(0), count: -1 })
    }
    if (currentWeek.length > 0) weeks.push(currentWeek)

    return (
      <div className="overflow-x-auto">
        <div className="inline-flex flex-col gap-1 min-w-max">
          {/* Month labels */}
          <div className="flex gap-1 ml-8">
            {months.map((m) => (
              <div key={m} className="text-xs text-slate-500 dark:text-slate-400" style={{ width: `${(weeks.length / 12) * 13}px` }}>
                {m}
              </div>
            ))}
          </div>

          {/* Heatmap grid */}
          <div className="flex gap-1">
            {/* Day labels */}
            <div className="flex flex-col gap-1 text-xs text-slate-500 dark:text-slate-400 w-6">
              {days.map((d, i) => (
                <div key={d} className="h-3 flex items-center">
                  {i % 2 === 1 ? d.substring(0, 1) : ''}
                </div>
              ))}
            </div>

            {/* Weeks */}
            {weeks.map((week, wi) => (
              <div key={wi} className="flex flex-col gap-1">
                {week.map((day, di) => (
                  <div
                    key={di}
                    onClick={() => {
                      if (day.count > 0) {
                        const dateStr = day.date.toISOString().split('T')[0]
                        navigate('/media', { state: { dateFrom: dateStr, dateTo: dateStr } })
                      }
                    }}
                    className={`w-3 h-3 rounded-sm ${day.count === -1 ? 'bg-transparent' : getColorIntensity(day.count)} ${day.count > 0 ? 'cursor-pointer hover:ring-1 hover:ring-blue-500' : ''}`}
                    title={day.count >= 0 ? `${day.date.toLocaleDateString()}: ${day.count} files` : ''}
                  />
                ))}
              </div>
            ))}
          </div>

          {/* Legend */}
          <div className="flex items-center gap-2 mt-2 ml-8 text-xs text-slate-500 dark:text-slate-400">
            <span>Less</span>
            <div className="w-3 h-3 rounded-sm bg-slate-100 dark:bg-slate-800" />
            <div className="w-3 h-3 rounded-sm bg-green-200 dark:bg-green-900" />
            <div className="w-3 h-3 rounded-sm bg-green-400 dark:bg-green-700" />
            <div className="w-3 h-3 rounded-sm bg-green-500 dark:bg-green-600" />
            <div className="w-3 h-3 rounded-sm bg-green-600 dark:bg-green-500" />
            <span>More</span>
          </div>
        </div>
      </div>
    )
  }

  // Navigate to Media page with smart folder filters
  const openSmartFolder = (folder: SmartFolder) => {
    const filters = folder.filters
    const state: any = {}

    if (filters.platform) state.platform = filters.platform
    if (filters.media_type) state.mediaType = filters.media_type
    if (filters.source) state.source = filters.source
    if (filters.size_min) state.sizeMin = filters.size_min

    navigate('/media', { state })
  }

  // Get folder icon component
  const getFolderIcon = (iconName: string) => {
    const icons: Record<string, any> = {
      folder: Folder,
      clock: Clock,
      image: Image,
      video: Video,
      star: Tags,
      heart: Tags,
      bookmark: Tags,
      tag: Tags,
      archive: Library,
      file: Tags,
      camera: Camera,
      'message-circle': MessageCircle,
      film: Film,
      youtube: Youtube,
      tv: Tv,
      zap: Zap,
      instagram: Camera,
      'hard-drive': HardDrive,
    }
    const Icon = icons[iconName] || Folder
    return Icon
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
            <Compass className="w-8 h-8 text-indigo-500" />
            Content Discovery
          </h1>
          <p className="text-slate-600 dark:text-slate-400 mt-1">
            Organize and explore your media with tags, smart folders, and collections
          </p>
        </div>
      </div>

      {/* Tabs */}
      <div className="border-b border-slate-200 dark:border-slate-700">
        <nav className="flex space-x-8">
          {[
            { id: 'search', label: 'AI Search', icon: Sparkles },
            { id: 'smart-folders', label: 'Smart Folders', icon: FolderSearch },
            { id: 'timeline', label: 'Timeline', icon: Calendar },
            { id: 'activity', label: 'Recent Activity', icon: Activity },
          ].map(tab => {
            const Icon = tab.icon
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as any)}
                className={`flex items-center gap-2 py-4 px-1 border-b-2 font-medium text-sm transition-colors ${
                  activeTab === tab.id
                    ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                    : 'border-transparent text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200'
                }`}
              >
                <Icon className="w-5 h-5" />
                {tab.label}
              </button>
            )
          })}
        </nav>
      </div>

      {/* Tab Content */}
      <div className="card-glass-hover rounded-xl p-6">

        {/* AI Search Tab */}
        {activeTab === 'search' && (
          <div className="space-y-6">
            {/* Search Header with Stats */}
            <div className="flex items-center justify-between flex-wrap gap-4">
              <div>
                <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">
                  Semantic Search
                </h2>
                <p className="text-sm text-slate-500 dark:text-slate-400 mt-1">
                  Search your media using natural language descriptions
                </p>
              </div>

              {semanticStats && (
                <div className="flex items-center gap-4 text-sm">
                  <div className="px-3 py-1.5 bg-slate-100 dark:bg-slate-800 rounded-lg">
                    <span className="text-slate-500 dark:text-slate-400">Coverage: </span>
                    <span className="font-medium text-slate-900 dark:text-slate-100">
                      {semanticStats.coverage_percent}%
                    </span>
                  </div>
                  <div className="px-3 py-1.5 bg-slate-100 dark:bg-slate-800 rounded-lg">
                    <span className="text-slate-500 dark:text-slate-400">Indexed: </span>
                    <span className="font-medium text-slate-900 dark:text-slate-100">
                      {semanticStats.total_embeddings.toLocaleString()} / {semanticStats.total_files.toLocaleString()}
                    </span>
                  </div>
                  {semanticStats.missing_embeddings > 0 && !isIndexing && (
                    <button
                      onClick={() => generateEmbeddingsMutation.mutate({ limit: 500 })}
                      disabled={generateEmbeddingsMutation.isPending}
                      className="px-3 py-1.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center gap-2 btn-hover-lift"
                    >
                      {generateEmbeddingsMutation.isPending ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <Sparkles className="w-4 h-4" />
                      )}
                      Index More
                    </button>
                  )}
                  {isIndexing && (
                    <div className="flex items-center gap-2 px-3 py-1.5 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
                      <Loader2 className="w-4 h-4 animate-spin text-blue-600 dark:text-blue-400" />
                      <span className="text-sm text-blue-700 dark:text-blue-300">Indexing...</span>
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* Search Input */}
            <div className="relative">
              <div className="flex gap-2">
                <div className="relative flex-1">
                  <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-slate-400" />
                  <input
                    type="text"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    onKeyDown={(e) => e.key === 'Enter' && performSearch()}
                    placeholder="Describe what you're looking for... (e.g., 'sunset on the beach', 'person wearing red dress', 'city skyline at night')"
                    className="w-full pl-12 pr-4 py-3 rounded-xl border border-border bg-background text-foreground input-glow focus-ring"
                  />
                </div>
                <button
                  onClick={performSearch}
                  disabled={isSearching || !searchQuery.trim()}
                  className="px-6 py-3 bg-blue-600 text-white rounded-xl hover:bg-blue-700 disabled:opacity-50 flex items-center gap-2 font-medium btn-hover-lift"
                >
                  {isSearching ? (
                    <Loader2 className="w-5 h-5 animate-spin" />
                  ) : (
                    <Sparkles className="w-5 h-5" />
                  )}
                  Search
                </button>
              </div>
            </div>

            {/* Example Queries */}
            {!hasSearched && (
              <div className="bg-secondary/50 rounded-lg p-4">
                <h3 className="text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  Try searching for:
                </h3>
                <div className="flex flex-wrap gap-2">
                  {[
                    'person smiling',
                    'beach sunset',
                    'group photo',
                    'food on a plate',
                    'selfie',
                    'landscape mountains',
                    'city at night',
                    'pet dog or cat',
                  ].map((example) => (
                    <button
                      key={example}
                      onClick={() => {
                        setSearchQuery(example)
                      }}
                      className="px-3 py-1.5 bg-background border border-border rounded-lg text-sm text-muted-foreground hover:border-primary hover:text-primary transition-colors"
                    >
                      {example}
                    </button>
                  ))}
                </div>
              </div>
            )}

            {/* Search Results */}
            {hasSearched && (
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <h3 className="text-sm font-medium text-slate-700 dark:text-slate-300">
                    {isSearching ? 'Searching...' : `Found ${searchResults.length} results`}
                  </h3>
                  {searchResults.length > 0 && (
                    <button
                      onClick={() => {
                        setSearchQuery('')
                        setSearchResults([])
                        setHasSearched(false)
                      }}
                      className="text-sm text-slate-500 hover:text-slate-700 dark:hover:text-slate-300"
                    >
                      Clear results
                    </button>
                  )}
                </div>

                {isSearching ? (
                  <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                    {[...Array(20)].map((_, i) => (
                      <div key={i} className="aspect-square bg-slate-200 dark:bg-slate-800 rounded-lg animate-pulse" />
                    ))}
                  </div>
                ) : searchResults.length > 0 ? (
                  <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                    {searchResults.map((result, index) => {
                      const isVideo = result.content_type === 'video' || isVideoFile(result.filename)

                      return (
                        <div
                          key={result.id}
                          onClick={() => setLightboxIndex(index)}
                          className="group relative aspect-square bg-slate-100 dark:bg-slate-800 rounded-lg overflow-hidden cursor-pointer hover:ring-2 hover:ring-blue-500 transition-all"
                        >
                          {/* Thumbnail */}
                          <ThrottledImage
                            src={api.getMediaThumbnailUrl(result.file_path, isVideo ? 'video' : 'image', result.file_token)}
                            alt={result.filename}
                            className="w-full h-full object-cover"
                          />

                          {/* Video indicator */}
                          {isVideo && (
                            <div className="absolute top-2 right-2 bg-black/70 rounded-full p-1.5 z-10">
                              <Play className="w-4 h-4 text-white fill-white" />
                            </div>
                          )}

                          {/* Similarity score badge */}
                          <div className="absolute top-2 left-2 px-1.5 py-0.5 bg-blue-600 text-white text-xs font-medium rounded z-10">
                            {Math.round(result.similarity * 100)}%
                          </div>

                          {/* Action buttons overlay */}
                          <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">
                            <button
                              onClick={(e) => {
                                e.stopPropagation()
                                handleMoveToReview(result.file_path)
                              }}
                              disabled={moveToReviewMutation.isPending}
                              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()
                                navigate('/media', { state: { selectedFileId: result.id } })
                              }}
                              className="w-full px-3 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center justify-center space-x-2 text-sm btn-hover-lift min-h-[44px] transition-colors"
                            >
                              <UserPlus className="w-4 h-4" />
                              <span>Add Reference</span>
                            </button>
                            <button
                              onClick={(e) => {
                                e.stopPropagation()
                                handleDelete(result)
                              }}
                              disabled={deleteMutation.isPending}
                              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>
                          </div>

                          {/* File info */}
                          <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 pointer-events-none">
                            <p className="text-white text-xs truncate">{result.filename}</p>
                            <p className="text-white/70 text-xs">{formatBytes(result.file_size)}</p>
                          </div>
                        </div>
                      )
                    })}
                  </div>
                ) : (
                  <div className="text-center py-12 text-slate-500 dark:text-slate-400">
                    <Search className="w-12 h-12 mx-auto mb-3 opacity-50" />
                    <p>No results found for "{searchQuery}"</p>
                    <p className="text-sm mt-1">Try a different description or index more files</p>
                  </div>
                )}
              </div>
            )}
          </div>
        )}

        {/* Smart Folders Tab */}
        {activeTab === 'smart-folders' && (
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">
                Smart Folders ({smartFoldersData?.length || 0})
              </h2>
              <button
                onClick={() => {
                  setEditingFolder(null)
                  setFolderForm({ name: '', icon: 'folder', color: '#6366f1', description: '', filters: {} })
                  setShowFolderModal(true)
                }}
                className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors btn-hover-lift"
              >
                <Plus className="w-4 h-4" />
                New Smart Folder
              </button>
            </div>

            {foldersLoading ? (
              <div className="text-center py-8 text-slate-500">Loading smart folders...</div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {smartFoldersData?.map(folder => {
                  const Icon = getFolderIcon(folder.icon)
                  const stats = folderStatsData?.stats?.[folder.id]
                  const fileCount = stats?.count ?? 0
                  const previews = stats?.previews ?? []

                  return (
                    <div
                      key={folder.id}
                      onClick={() => openSmartFolder(folder)}
                      className="card-glass-hover p-4 rounded-xl group cursor-pointer"
                    >
                      <div className="flex items-start justify-between">
                        <div className="flex items-center gap-3">
                          <div
                            className="w-10 h-10 rounded-lg flex items-center justify-center"
                            style={{ backgroundColor: `${folder.color}20` }}
                          >
                            <Icon className="w-5 h-5" style={{ color: folder.color }} />
                          </div>
                          <div>
                            <h3 className="font-medium text-slate-900 dark:text-slate-100 flex items-center gap-2">
                              {folder.name}
                              {/* File count badge */}
                              <span className="px-2 py-0.5 text-xs font-medium bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 rounded-full">
                                {fileCount.toLocaleString()}
                              </span>
                              <ExternalLink className="w-3 h-3 opacity-0 group-hover:opacity-50" />
                            </h3>
                            {folder.description && (
                              <p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5">
                                {folder.description}
                              </p>
                            )}
                          </div>
                        </div>

                        {!folder.is_system && (
                          <div className="opacity-0 group-hover:opacity-100 flex gap-1">
                            <button
                              onClick={(e) => {
                                e.stopPropagation()
                                setEditingFolder(folder)
                                setFolderForm({
                                  name: folder.name,
                                  icon: folder.icon,
                                  color: folder.color,
                                  description: folder.description || '',
                                  filters: folder.filters
                                })
                                setShowFolderModal(true)
                              }}
                              className="p-1 rounded hover:bg-slate-200 dark:hover:bg-slate-700"
                            >
                              <Edit2 className="w-4 h-4 text-slate-500" />
                            </button>
                            <button
                              onClick={(e) => {
                                e.stopPropagation()
                                if (confirm(`Delete smart folder "${folder.name}"?`)) {
                                  deleteFolderMutation.mutate(folder.id)
                                }
                              }}
                              className="p-1 rounded hover:bg-red-100 dark:hover:bg-red-900/30"
                            >
                              <Trash2 className="w-4 h-4 text-red-500" />
                            </button>
                          </div>
                        )}
                      </div>

                      {/* Preview thumbnails */}
                      {previews.length > 0 && (
                        <div className="mt-3 grid grid-cols-4 gap-1">
                          {previews.map((preview, idx) => (
                            <div key={idx} className="aspect-square rounded overflow-hidden bg-slate-100 dark:bg-slate-800">
                              <ThrottledImage
                                src={api.getMediaThumbnailUrl(preview.file_path, preview.content_type === 'video' ? 'video' : 'image', preview.file_token)}
                                alt=""
                                className="w-full h-full object-cover"
                              />
                            </div>
                          ))}
                          {/* Fill remaining slots with empty placeholders */}
                          {[...Array(Math.max(0, 4 - previews.length))].map((_, idx) => (
                            <div key={`empty-${idx}`} className="aspect-square rounded bg-slate-100 dark:bg-slate-800" />
                          ))}
                        </div>
                      )}

                      {folder.is_system && (
                        <span className="inline-block mt-2 px-2 py-0.5 text-xs bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 rounded">
                          System
                        </span>
                      )}
                    </div>
                  )
                })}
              </div>
            )}
          </div>
        )}

        {/* Timeline Tab */}
        {activeTab === 'timeline' && (
          <div className="space-y-6">
            <div className="flex items-center justify-between flex-wrap gap-4">
              <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">
                Activity Timeline
              </h2>

              <div className="flex items-center gap-4">
                {/* Year selector for heatmap */}
                <select
                  value={timelineYear}
                  onChange={(e) => setTimelineYear(parseInt(e.target.value))}
                  className="px-3 py-2 rounded-lg border border-border bg-background text-foreground"
                >
                  {Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - i).map(year => (
                    <option key={year} value={year}>{year}</option>
                  ))}
                </select>

                {/* Granularity selector */}
                <select
                  value={timelineGranularity}
                  onChange={(e) => setTimelineGranularity(e.target.value as any)}
                  className="px-3 py-2 rounded-lg border border-border bg-background text-foreground"
                >
                  <option value="day">Daily</option>
                  <option value="week">Weekly</option>
                  <option value="month">Monthly</option>
                  <option value="year">Yearly</option>
                </select>
              </div>
            </div>

            {/* Period Stats Summary */}
            {timelineData && timelineData.length > 0 && (
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                {(() => {
                  const totals = timelineData.reduce((acc, entry) => ({
                    files: acc.files + entry.file_count,
                    images: acc.images + entry.image_count,
                    videos: acc.videos + entry.video_count,
                    size: acc.size + entry.total_size,
                  }), { files: 0, images: 0, videos: 0, size: 0 })

                  return (
                    <>
                      <div className="card-glass-hover rounded-xl p-4 text-center border stat-card-blue shadow-blue-glow">
                        <div className="text-2xl font-bold text-blue-600 dark:text-blue-400">
                          {totals.files.toLocaleString()}
                        </div>
                        <div className="text-sm text-muted-foreground">Total Files</div>
                      </div>
                      <div className="card-glass-hover rounded-xl p-4 text-center border stat-card-cyan">
                        <div className="text-2xl font-bold text-cyan-600 dark:text-cyan-400">
                          {totals.images.toLocaleString()}
                        </div>
                        <div className="text-sm text-muted-foreground">Images</div>
                      </div>
                      <div className="card-glass-hover rounded-xl p-4 text-center border stat-card-purple shadow-purple-glow">
                        <div className="text-2xl font-bold text-violet-600 dark:text-violet-400">
                          {totals.videos.toLocaleString()}
                        </div>
                        <div className="text-sm text-muted-foreground">Videos</div>
                      </div>
                      <div className="card-glass-hover rounded-xl p-4 text-center border stat-card-green shadow-green-glow">
                        <div className="text-2xl font-bold text-emerald-600 dark:text-emerald-400">
                          {formatBytes(totals.size)}
                        </div>
                        <div className="text-sm text-muted-foreground">Total Size</div>
                      </div>
                    </>
                  )
                })()}
              </div>
            )}

            {/* Activity Heatmap */}
            <div className="bg-secondary/50 rounded-xl p-4">
              <h3 className="text-sm font-medium text-foreground mb-4">
                Activity Heatmap - {timelineYear}
              </h3>
              {renderHeatmap()}
            </div>

            {/* Timeline List */}
            {timelineLoading ? (
              <div className="text-center py-8 text-slate-500">Loading timeline...</div>
            ) : timelineData && timelineData.length > 0 ? (
              <div className="space-y-2">
                {timelineData.map((entry) => {
                  // Calculate date range based on granularity
                  const getDateRange = () => {
                    const dateStr = entry.date
                    if (timelineGranularity === 'day') {
                      return { dateFrom: dateStr, dateTo: dateStr }
                    } else if (timelineGranularity === 'week') {
                      // entry.date is the start of the week (YYYY-MM-DD)
                      const startDate = new Date(dateStr)
                      const endDate = new Date(startDate)
                      endDate.setDate(endDate.getDate() + 6)
                      return { dateFrom: dateStr, dateTo: endDate.toISOString().split('T')[0] }
                    } else if (timelineGranularity === 'month') {
                      // entry.date is YYYY-MM
                      const [year, month] = dateStr.split('-').map(Number)
                      const startDate = `${year}-${String(month).padStart(2, '0')}-01`
                      const endDate = new Date(year, month, 0) // Last day of month
                      return { dateFrom: startDate, dateTo: endDate.toISOString().split('T')[0] }
                    } else if (timelineGranularity === 'year') {
                      // entry.date is YYYY
                      return { dateFrom: `${dateStr}-01-01`, dateTo: `${dateStr}-12-31` }
                    }
                    return { dateFrom: dateStr, dateTo: dateStr }
                  }

                  return (
                    <div
                      key={entry.date}
                      onClick={() => navigate('/media', { state: getDateRange() })}
                      className="flex items-center gap-4 p-4 rounded-xl border border-border hover:bg-secondary/50 cursor-pointer hover:border-primary transition-colors"
                    >
                      <div className="w-24 text-sm font-medium text-slate-900 dark:text-slate-100">
                        {entry.date}
                      </div>

                      <div className="flex-1 flex items-center gap-6">
                        <div className="flex items-center gap-2 text-slate-600 dark:text-slate-400">
                          <HardDrive className="w-4 h-4" />
                          <span className="text-sm">{entry.file_count} files</span>
                        </div>

                        <div className="flex items-center gap-2 text-slate-600 dark:text-slate-400">
                          <Image className="w-4 h-4" />
                          <span className="text-sm">{entry.image_count} images</span>
                        </div>

                        <div className="flex items-center gap-2 text-slate-600 dark:text-slate-400">
                          <Video className="w-4 h-4" />
                          <span className="text-sm">{entry.video_count} videos</span>
                        </div>

                        <div className="flex items-center gap-2 text-slate-600 dark:text-slate-400">
                          <Filter className="w-4 h-4" />
                          <span className="text-sm">{formatBytes(entry.total_size)}</span>
                        </div>
                      </div>

                      <ExternalLink className="w-4 h-4 text-slate-400 opacity-0 group-hover:opacity-100" />
                    </div>
                  )
                })}
              </div>
            ) : (
              <div className="text-center py-8 text-slate-500 dark:text-slate-400">
                No timeline data available.
              </div>
            )}
          </div>
        )}

        {/* Recent Activity Tab */}
        {activeTab === 'activity' && (
          <div className="space-y-6">
            <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">
              Recent Activity
            </h2>

            {/* Summary Stats */}
            {activityData && (
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div className="card-glass-hover rounded-xl p-4 text-center border stat-card-green shadow-green-glow">
                  <div className="text-2xl font-bold text-emerald-600 dark:text-emerald-400">
                    {activityData.summary.downloads_24h}
                  </div>
                  <div className="text-sm text-muted-foreground">Downloads (24h)</div>
                </div>
                <div className="card-glass-hover rounded-xl p-4 text-center border stat-card-blue shadow-blue-glow">
                  <div className="text-2xl font-bold text-blue-600 dark:text-blue-400">
                    {activityData.summary.downloads_7d}
                  </div>
                  <div className="text-sm text-muted-foreground">Downloads (7d)</div>
                </div>
                <div className="card-glass-hover rounded-xl p-4 text-center border stat-card-red shadow-red-glow">
                  <div className="text-2xl font-bold text-red-600 dark:text-red-400">
                    {activityData.summary.deleted_24h}
                  </div>
                  <div className="text-sm text-muted-foreground">Deleted (24h)</div>
                </div>
                <div className="card-glass-hover rounded-xl p-4 text-center border stat-card-orange shadow-orange-glow">
                  <div className="text-2xl font-bold text-amber-600 dark:text-amber-400">
                    {activityData.summary.deleted_7d}
                  </div>
                  <div className="text-sm text-muted-foreground">Deleted (7d)</div>
                </div>
              </div>
            )}

            {activityLoading ? (
              <div className="text-center py-8 text-slate-500">
                <Loader2 className="w-6 h-6 animate-spin mx-auto mb-2" />
                Loading activity...
              </div>
            ) : (
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Recent Downloads */}
                <div className="card-glass rounded-xl border border-border overflow-hidden">
                  <div className="px-4 py-3 bg-green-500/10 border-b border-border flex items-center gap-2">
                    <Download className="w-4 h-4 text-green-600 dark:text-green-400" />
                    <h3 className="font-medium text-green-800 dark:text-green-300">Recent Downloads</h3>
                  </div>
                  <div className="divide-y divide-slate-100 dark:divide-slate-700 max-h-80 overflow-y-auto custom-scrollbar">
                    {activityData?.recent_downloads.length === 0 ? (
                      <div className="p-4 text-sm text-slate-500 text-center">No recent downloads</div>
                    ) : (
                      activityData?.recent_downloads.map((item) => (
                        <div
                          key={item.id}
                          className="p-3 hover:bg-slate-50 dark:hover:bg-slate-700/50 flex items-center gap-3 cursor-pointer"
                          onClick={() => navigate('/media')}
                        >
                          <div className="w-10 h-10 rounded bg-slate-100 dark:bg-slate-700 overflow-hidden flex-shrink-0">
                            <ThrottledImage
                              src={api.getMediaThumbnailUrl(item.file_path, item.content_type === 'video' ? 'video' : 'image', item.file_token)}
                              alt=""
                              className="w-full h-full object-cover"
                            />
                          </div>
                          <div className="flex-1 min-w-0">
                            <div className="text-sm font-medium text-slate-900 dark:text-slate-100 truncate">
                              {item.filename}
                            </div>
                            <div className="text-xs text-slate-500 dark:text-slate-400 flex items-center gap-2">
                              <span>{item.platform}</span>
                              <span>·</span>
                              <span>{formatBytes(item.file_size)}</span>
                              <span>·</span>
                              <span>{new Date(item.timestamp).toLocaleDateString()}</span>
                            </div>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                </div>

                {/* Recent Deleted */}
                <div className="card-glass rounded-xl border border-border overflow-hidden">
                  <div className="px-4 py-3 bg-red-500/10 border-b border-border flex items-center gap-2">
                    <Trash2 className="w-4 h-4 text-red-600 dark:text-red-400" />
                    <h3 className="font-medium text-red-800 dark:text-red-300">Recently Deleted</h3>
                  </div>
                  <div className="divide-y divide-slate-100 dark:divide-slate-700 max-h-80 overflow-y-auto custom-scrollbar">
                    {activityData?.recent_deleted.length === 0 ? (
                      <div className="p-4 text-sm text-slate-500 text-center">No recent deletions</div>
                    ) : (
                      activityData?.recent_deleted.map((item) => (
                        <div
                          key={item.id}
                          className="p-3 hover:bg-slate-50 dark:hover:bg-slate-700/50 flex items-center gap-3"
                        >
                          <div className="w-10 h-10 rounded bg-slate-100 dark:bg-slate-700 overflow-hidden flex-shrink-0">
                            <ThrottledImage
                              src={api.getMediaThumbnailUrl(item.file_path, item.content_type === 'video' ? 'video' : 'image', item.file_token)}
                              alt=""
                              className="w-full h-full object-cover opacity-60"
                            />
                          </div>
                          <div className="flex-1 min-w-0">
                            <div className="text-sm font-medium text-slate-900 dark:text-slate-100 truncate">
                              {item.filename}
                            </div>
                            <div className="text-xs text-slate-500 dark:text-slate-400 flex items-center gap-2">
                              <span>{item.platform}</span>
                              <span>·</span>
                              <span>{formatBytes(item.file_size)}</span>
                              <span>·</span>
                              <span>from {item.deleted_from}</span>
                            </div>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                </div>

                {/* Pending Review */}
                <div className="card-glass rounded-xl border border-border overflow-hidden lg:col-span-2">
                  <div className="px-4 py-3 bg-amber-500/10 border-b border-border flex items-center gap-2">
                    <Eye className="w-4 h-4 text-amber-600 dark:text-amber-400" />
                    <h3 className="font-medium text-amber-800 dark:text-amber-300">Pending Review</h3>
                    <button
                      onClick={() => navigate('/review')}
                      className="ml-auto text-xs text-amber-600 dark:text-amber-400 hover:underline"
                    >
                      Go to Review →
                    </button>
                  </div>
                  <div className="p-3">
                    {activityData?.recent_moved_to_review.length === 0 ? (
                      <div className="text-sm text-slate-500 text-center py-2">No files pending review</div>
                    ) : (
                      <div className="flex flex-wrap gap-2">
                        {activityData?.recent_moved_to_review.slice(0, 8).map((item) => (
                          <div
                            key={item.id}
                            className="w-16 h-16 rounded bg-slate-100 dark:bg-slate-700 overflow-hidden cursor-pointer hover:ring-2 hover:ring-amber-500"
                            onClick={() => navigate('/review')}
                            title={item.filename}
                          >
                            <ThrottledImage
                              src={api.getMediaThumbnailUrl(item.file_path, item.content_type === 'video' ? 'video' : 'image', item.file_token)}
                              alt=""
                              className="w-full h-full object-cover"
                            />
                          </div>
                        ))}
                        {(activityData?.recent_moved_to_review.length || 0) > 8 && (
                          <div
                            className="w-16 h-16 rounded bg-slate-200 dark:bg-slate-600 flex items-center justify-center cursor-pointer hover:bg-slate-300 dark:hover:bg-slate-500"
                            onClick={() => navigate('/review')}
                          >
                            <span className="text-sm font-medium text-slate-600 dark:text-slate-300">
                              +{(activityData?.recent_moved_to_review.length || 0) - 8}
                            </span>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Smart Folder Modal */}
      {showFolderModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-card border border-border rounded-xl shadow-2xl w-full max-w-lg p-6">
            <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">
              {editingFolder ? 'Edit Smart Folder' : 'Create Smart Folder'}
            </h3>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                  Name
                </label>
                <input
                  type="text"
                  value={folderForm.name}
                  onChange={(e) => setFolderForm({ ...folderForm, name: e.target.value })}
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground"
                  placeholder="Folder name"
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                    Icon
                  </label>
                  <select
                    value={folderForm.icon}
                    onChange={(e) => setFolderForm({ ...folderForm, icon: e.target.value })}
                    className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground"
                  >
                    {FOLDER_ICONS.map(icon => (
                      <option key={icon} value={icon}>{icon}</option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                    Color
                  </label>
                  <div className="flex flex-wrap gap-1">
                    {TAG_COLORS.slice(0, 8).map(color => (
                      <button
                        key={color}
                        onClick={() => setFolderForm({ ...folderForm, color })}
                        className={`w-6 h-6 rounded-full border-2 ${
                          folderForm.color === color ? 'border-slate-900 dark:border-white' : 'border-transparent'
                        }`}
                        style={{ backgroundColor: color }}
                      />
                    ))}
                  </div>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                  Description (optional)
                </label>
                <textarea
                  value={folderForm.description}
                  onChange={(e) => setFolderForm({ ...folderForm, description: e.target.value })}
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground"
                  rows={2}
                  placeholder="What this smart folder contains"
                />
              </div>

              {/* Filter builder with dropdowns */}
              <div className="space-y-3">
                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300">
                  Filters
                </label>

                <div className="grid grid-cols-2 gap-3">
                  {/* Platform filter */}
                  <div>
                    <label className="block text-xs text-slate-500 dark:text-slate-400 mb-1">
                      Platform
                    </label>
                    <select
                      value={folderForm.filters.platform || ''}
                      onChange={(e) => {
                        const newFilters = { ...folderForm.filters }
                        if (e.target.value) {
                          newFilters.platform = e.target.value
                        } else {
                          delete newFilters.platform
                        }
                        setFolderForm({ ...folderForm, filters: newFilters })
                      }}
                      className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground text-sm"
                    >
                      <option value="">Any platform</option>
                      <option value="instagram">Instagram</option>
                      <option value="tiktok">TikTok</option>
                      <option value="snapchat">Snapchat</option>
                      <option value="youtube">YouTube</option>
                      <option value="forums">Forums</option>
                      <option value="coppermine">Coppermine</option>
                      <option value="manual">Manual Import</option>
                    </select>
                  </div>

                  {/* Media type filter */}
                  <div>
                    <label className="block text-xs text-slate-500 dark:text-slate-400 mb-1">
                      Media Type
                    </label>
                    <select
                      value={folderForm.filters.media_type || ''}
                      onChange={(e) => {
                        const newFilters = { ...folderForm.filters }
                        if (e.target.value) {
                          newFilters.media_type = e.target.value
                        } else {
                          delete newFilters.media_type
                        }
                        setFolderForm({ ...folderForm, filters: newFilters })
                      }}
                      className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground text-sm"
                    >
                      <option value="">Any type</option>
                      <option value="image">Images only</option>
                      <option value="video">Videos only</option>
                    </select>
                  </div>
                </div>

                {/* Source filter (text input for flexibility) */}
                <div>
                  <label className="block text-xs text-slate-500 dark:text-slate-400 mb-1">
                    Source (username/account)
                  </label>
                  <input
                    type="text"
                    value={folderForm.filters.source || ''}
                    onChange={(e) => {
                      const newFilters = { ...folderForm.filters }
                      if (e.target.value) {
                        newFilters.source = e.target.value
                      } else {
                        delete newFilters.source
                      }
                      setFolderForm({ ...folderForm, filters: newFilters })
                    }}
                    placeholder="e.g., username"
                    className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground text-sm"
                  />
                </div>

                {/* Size filter */}
                <div>
                  <label className="block text-xs text-slate-500 dark:text-slate-400 mb-1">
                    Minimum Size
                  </label>
                  <select
                    value={folderForm.filters.size_min || ''}
                    onChange={(e) => {
                      const newFilters = { ...folderForm.filters }
                      if (e.target.value) {
                        newFilters.size_min = parseInt(e.target.value)
                      } else {
                        delete newFilters.size_min
                      }
                      setFolderForm({ ...folderForm, filters: newFilters })
                    }}
                    className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground text-sm"
                  >
                    <option value="">Any size</option>
                    <option value="102400">100 KB+</option>
                    <option value="524288">500 KB+</option>
                    <option value="1048576">1 MB+</option>
                    <option value="5242880">5 MB+</option>
                    <option value="10485760">10 MB+</option>
                    <option value="52428800">50 MB+</option>
                  </select>
                </div>

                {/* Active filters summary */}
                {Object.keys(folderForm.filters).length > 0 && (
                  <div className="flex flex-wrap gap-1 pt-1">
                    {Object.entries(folderForm.filters).map(([key, value]) => (
                      <span
                        key={key}
                        className="inline-flex items-center gap-1 px-2 py-0.5 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 text-xs rounded"
                      >
                        {key}: {typeof value === 'number' ? formatBytes(value) : value}
                        <button
                          onClick={() => {
                            const newFilters = { ...folderForm.filters }
                            delete newFilters[key]
                            setFolderForm({ ...folderForm, filters: newFilters })
                          }}
                          className="hover:text-blue-900 dark:hover:text-blue-100"
                        >
                          ×
                        </button>
                      </span>
                    ))}
                  </div>
                )}
              </div>
            </div>

            <div className="flex justify-end gap-3 mt-6">
              <button
                onClick={() => {
                  setShowFolderModal(false)
                  setEditingFolder(null)
                }}
                className="px-4 py-2 rounded-lg border border-border text-muted-foreground hover:bg-secondary transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={() => {
                  if (editingFolder) {
                    updateFolderMutation.mutate({ id: editingFolder.id, data: folderForm })
                  } else {
                    createFolderMutation.mutate(folderForm)
                  }
                }}
                disabled={!folderForm.name.trim()}
                className="px-4 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed btn-hover-lift"
              >
                {editingFolder ? 'Update' : 'Create'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Search Results Lightbox */}
      {lightboxIndex >= 0 && searchResults.length > 0 && (
        <EnhancedLightbox
          items={searchResults.map(r => ({
            file_path: r.file_path,
            file_token: r.file_token,
            filename: r.filename,
            platform: r.platform,
            source: r.source,
            file_size: r.file_size,
            content_type: r.content_type,
            media_type: r.content_type === 'video' ? 'video' : 'image',
            similarity: r.similarity,
            id: r.id
          }))}
          currentIndex={lightboxIndex}
          onClose={() => setLightboxIndex(-1)}
          onNavigate={(index) => setLightboxIndex(index)}
          onDelete={handleDelete}
          getPreviewUrl={(item) => api.getMediaPreviewUrl(item.file_path, item.file_token)}
          getThumbnailUrl={(item) => api.getMediaThumbnailUrl(item.file_path, item.media_type as 'image' | 'video', item.file_token)}
          isVideo={(item) => item.content_type === 'video' || isVideoFile(item.filename)}
          renderActions={(item: any) => (
            <>
              <button
                onClick={() => handleMoveToReview(item.file_path)}
                disabled={moveToReviewMutation.isPending}
                className="px-6 py-3 bg-orange-600 text-white rounded-lg hover:bg-orange-700 disabled:opacity-50 flex items-center space-x-2 transition-colors"
              >
                <Eye className="w-5 h-5" />
                <span>{moveToReviewMutation.isPending ? 'Moving...' : 'Move to Review'}</span>
              </button>
              <button
                onClick={() => navigate('/media', { state: { selectedFileId: item.id } })}
                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 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={() => handleDelete(item)}
                disabled={deleteMutation.isPending}
                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>
            </>
          )}
        />
      )}
    </div>
  )
}
