'use client'

import {
  Upload,
  Grid3x3,
  List,
  Search,
  Trash2,
  Download,
  FileText,
  ArrowUpDown,
  ArrowUp,
  ArrowDown,
  X,
  Bot,
  Sparkles,
  Link2,
  AlertTriangle,
  Copy,
  ExternalLink,
  ImageIcon,
  FileImage,
  Loader2,
  FolderInput,
  GripVertical,
} from 'lucide-react'
import { useState, useMemo, useRef, useCallback } from 'react'
import { toast } from 'sonner'
import { sortByRelevance, type SortConfig, toggleSort } from '../lib/search.js'
import { useApiData } from '../lib/useApiData.js'
import { cmsApi } from '../lib/api.js'
import { FolderTree, type FolderSelection } from '../components/FolderTree.js'

interface MediaItem {
  id: number | string
  name: string
  type: string
  size: string
  sizeBytes: number
  date: string
  url: string
  dimensions?: string
  format?: string
  altTag?: string
  title?: string
  usedOn?: { page: string; path: string }[]
}

function isImageMedia(item: MediaItem): boolean {
  return (
    Boolean(item.url) &&
    (item.type?.startsWith('image/') || /\.(avif|gif|jpe?g|png|webp|svg)$/i.test(item.url))
  )
}

function matchesMediaType(item: MediaItem, filterType: string): boolean {
  if (filterType === 'all') return true
  if (filterType === 'image') return item.type?.startsWith('image/') || isImageMedia(item)
  if (filterType === 'video') return item.type?.startsWith('video/')
  if (filterType === 'document')
    return !item.type?.startsWith('image/') && !item.type?.startsWith('video/')
  return item.type === filterType
}

function MediaPreview({ item }: { item: MediaItem }) {
  if (isImageMedia(item)) {
    return (
      <img
        src={item.url}
        alt={item.altTag || item.title || item.name || 'Media preview'}
        className="h-full w-full object-cover"
        loading="lazy"
      />
    )
  }

  return <FileImage className="text-muted-foreground h-6 w-6 sm:h-8 sm:w-8" />
}

type MediaSortKey = 'name' | 'type' | 'size' | 'date'

export interface MediaBrowserProps {
  onNavigate?: (path: string) => void
}

function buildMediaApiUrl(folderSel: FolderSelection): string {
  const base = '/media?pageSize=100'
  if (folderSel.type === 'smart') {
    if (folderSel.smart === 'recent') return `${base}&sort=updatedAt&order=desc&pageSize=20`
    if (folderSel.smart === 'uncategorized') return `${base}&folderId=none`
    return base
  }
  return `${base}&folderId=${folderSel.folderId}`
}

export function MediaBrowser({ onNavigate }: MediaBrowserProps) {
  const [folderSel, setFolderSel] = useState<FolderSelection>({ type: 'smart', smart: 'all' })
  const [sidebarOpen, setSidebarOpen] = useState(true)

  const apiUrl = useMemo(() => buildMediaApiUrl(folderSel), [folderSel])
  const { data, loading, error, refetch } = useApiData<{
    data?: MediaItem[]
    items?: MediaItem[]
    total: number
  }>(apiUrl)

  const allData = useApiData<{ data: MediaItem[]; total: number }>('/media?pageSize=1')
  const uncatData = useApiData<{ data: MediaItem[]; total: number }>(
    '/media?pageSize=1&folderId=none',
  )

  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid')
  const [searchQuery, setSearchQuery] = useState('')
  const [filterType, setFilterType] = useState('all')
  const [selectedMedia, setSelectedMedia] = useState<Array<number | string>>([])
  const [sortConfig, setSortConfig] = useState<SortConfig<MediaSortKey> | null>(null)
  const [activeItem, setActiveItem] = useState<MediaItem | null>(null)

  const [editAlt, setEditAlt] = useState('')
  const [editTitle, setEditTitle] = useState('')
  const [editFilename, setEditFilename] = useState('')
  const [saving, setSaving] = useState(false)
  const [aiGenerating, setAiGenerating] = useState<string | null>(null)
  const [uploading, setUploading] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const mediaItems = data?.data ?? data?.items ?? []

  const filteredAndSorted = useMemo(() => {
    let results = mediaItems.filter((item) => {
      const matchesSearch = (item.name ?? '').toLowerCase().includes(searchQuery.toLowerCase())
      const matchesType = matchesMediaType(item, filterType)
      return matchesSearch && matchesType
    })

    if (searchQuery.trim()) {
      results = sortByRelevance(results, searchQuery, (m) => [m.name])
    } else if (sortConfig) {
      results = [...results].sort((a, b) => {
        let cmp: number
        if (sortConfig.key === 'size') {
          cmp = a.sizeBytes - b.sizeBytes
        } else {
          cmp = String(a[sortConfig.key]).localeCompare(String(b[sortConfig.key]))
        }
        return sortConfig.direction === 'asc' ? cmp : -cmp
      })
    }
    return results
  }, [mediaItems, searchQuery, filterType, sortConfig])

  const openDetail = (item: MediaItem) => {
    setActiveItem(item)
    setEditAlt(item.altTag ?? '')
    setEditTitle(item.title ?? '')
    setEditFilename(item.name)
  }

  const closeDetail = () => {
    setActiveItem(null)
  }

  const handleCheckbox = (e: React.MouseEvent, id: number | string) => {
    e.stopPropagation()
    setSelectedMedia((prev) =>
      prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id],
    )
  }

  const handleSelectAll = () => {
    setSelectedMedia((prev) =>
      prev.length === filteredAndSorted.length ? [] : filteredAndSorted.map((item) => item.id),
    )
  }

  const handleSaveDetails = async () => {
    if (!activeItem) return
    setSaving(true)
    const res = await cmsApi(`/media/${activeItem.id}`, {
      method: 'PUT',
      body: JSON.stringify({
        alt: editAlt,
        title: editTitle,
        filename: editFilename,
      }),
    })
    setSaving(false)
    if (res.error) {
      toast.error(res.error)
    } else {
      toast.success('Media details saved')
      refetch()
    }
  }

  const deleteMedia = async (id: number | string) => {
    const res = await cmsApi(`/media/${id}`, { method: 'DELETE' })
    if (res.error) {
      toast.error(res.error)
    } else {
      toast.success('Media deleted')
      if (activeItem?.id === id) closeDetail()
      refetch()
    }
  }

  const handleAiGenerate = async (field: 'alt' | 'title' | 'optimize') => {
    setAiGenerating(field)

    if (field === 'optimize' && activeItem) {
      const res = await cmsApi<
        MediaItem & {
          optimization?: {
            originalSize: number
            optimizedSize: number
            savings: number
            originalSizeFormatted: string
            optimizedSizeFormatted: string
            alreadyOptimized?: boolean
          }
        }
      >(`/media/${activeItem.id}/optimize`, { method: 'POST' })

      if (res.error) {
        toast.error(res.error)
      } else if ((res.data as any)?.optimization?.alreadyOptimized) {
        toast.info('Image is already in WebP format — no further optimization needed')
      } else if ((res.data as any)?.optimization) {
        const opt = (res.data as any).optimization
        toast.success(
          `Optimized: ${opt.originalSizeFormatted} → ${opt.optimizedSizeFormatted} (${opt.savings}% smaller)`,
        )
        refetch()
      }

      setAiGenerating(null)
      return
    }

    if (!activeItem) {
      setAiGenerating(null)
      return
    }

    const res = await cmsApi<{ alt?: string; title?: string; alternatives?: string[] }>(
      '/ai/media-metadata',
      { method: 'POST', body: JSON.stringify({ mediaId: activeItem.id }) },
    )

    if (res.error) {
      // AI plugin/provider not configured (e.g. local dev): fall back to a
      // basic filename-derived suggestion so the action still helps.
      const base = (activeItem.name ?? '')
        .replace(/\.\w+$/, '')
        .replace(/[-_]/g, ' ')
        .trim()
      if (field === 'alt') {
        setEditAlt(base ? `Image of ${base}` : '')
      } else {
        setEditTitle(base.replace(/\b\w/g, (c) => c.toUpperCase()))
      }
      toast.info('AI unavailable — generated a basic suggestion from the filename')
      setAiGenerating(null)
      return
    }

    if (field === 'alt') {
      setEditAlt(res.data?.alt ?? '')
      toast.success('Alt tag generated by AI')
    } else {
      setEditTitle(res.data?.title ?? '')
      toast.success('Title generated by AI')
    }
    setAiGenerating(null)
  }

  const handleCopyUrl = () => {
    if (activeItem?.url) {
      navigator.clipboard.writeText(activeItem.url)
      toast.success('URL copied to clipboard')
    }
  }

  const handleUploadFiles = async (files: FileList | null) => {
    if (!files || files.length === 0) return
    setUploading(true)

    let successCount = 0

    for (let i = 0; i < files.length; i++) {
      const file = files[i]!
      const formData = new FormData()
      formData.append('file', file)

      const res = await cmsApi<
        MediaItem & {
          optimization?: {
            originalSize: number
            optimizedSize: number
            savings: number
            originalSizeFormatted: string
            optimizedSizeFormatted: string
          }
        }
      >('/media/upload', { method: 'POST', body: formData })

      if (res.error) {
        toast.error(`Failed to upload ${file.name}: ${res.error}`)
      } else {
        const opt = (res.data as any)?.optimization
        if (opt && opt.savings > 0) {
          toast.success(
            `${file.name} → WebP (${opt.originalSizeFormatted} → ${opt.optimizedSizeFormatted}, ${opt.savings}% saved)`,
          )
        } else {
          toast.success(`Uploaded ${file.name}`)
        }
        successCount++
      }
    }

    if (successCount > 0) refetch()
    if (fileInputRef.current) fileInputRef.current.value = ''
    setUploading(false)
  }

  const handleDropItem = useCallback(
    async (itemId: string, folderId: string | null) => {
      const res = await cmsApi(`/media/${itemId}/folder`, {
        method: 'PUT',
        body: JSON.stringify({ folderId }),
      })
      if (res.error) {
        toast.error(res.error)
      } else {
        toast.success(folderId ? 'Moved to folder' : 'Removed from folder')
        refetch()
      }
    },
    [refetch],
  )

  const handleDragStart = (e: React.DragEvent, id: number | string) => {
    e.dataTransfer.setData('text/actuate-item-id', String(id))
    e.dataTransfer.effectAllowed = 'move'
  }

  const panelOpen = activeItem !== null
  const issues = activeItem
    ? [
        ...(!activeItem.altTag ? ['Missing alt tag'] : []),
        ...(!activeItem.title ? ['Missing title'] : []),
        ...(activeItem.sizeBytes > 2000000 ? ['File size over 2 MB — consider optimizing'] : []),
        ...(activeItem.usedOn?.length === 0 ? ['Not used on any page'] : []),
      ]
    : []

  function SortHeader({ label, sortKey }: { label: string; sortKey: MediaSortKey }) {
    const active = sortConfig?.key === sortKey
    return (
      <button
        type="button"
        onClick={() => setSortConfig(toggleSort(sortConfig, sortKey))}
        className="flex items-center gap-1 text-xs font-medium text-gray-700 transition-colors hover:text-gray-900"
      >
        {label}
        {active ? (
          sortConfig!.direction === 'asc' ? (
            <ArrowUp className="h-3 w-3" />
          ) : (
            <ArrowDown className="h-3 w-3" />
          )
        ) : (
          <ArrowUpDown className="h-3 w-3 text-gray-400" />
        )}
      </button>
    )
  }

  if (loading) {
    return (
      <div className="flex h-64 items-center justify-center p-3 pr-6 sm:p-4 sm:pr-8">
        <Loader2 className="h-6 w-6 animate-spin text-blue-600" />
      </div>
    )
  }

  return (
    <div className="flex h-full flex-col p-3 pr-6 sm:p-4 sm:pr-8">
      {error && (
        <div className="mb-4 flex items-center gap-3 rounded-lg border border-red-200 bg-red-50 p-3">
          <AlertTriangle className="h-5 w-5 shrink-0 text-red-600" />
          <span className="flex-1 text-sm text-red-800">{error}</span>
          <button
            onClick={refetch}
            className="rounded-lg border border-red-300 px-3 py-1 text-sm text-red-700 transition-colors hover:bg-red-100"
          >
            Retry
          </button>
        </div>
      )}

      <div className="mb-4 flex items-center justify-between">
        <div className="flex items-center gap-3">
          <button
            type="button"
            onClick={() => setSidebarOpen((prev) => !prev)}
            className="rounded-lg p-1.5 transition-colors hover:bg-gray-100"
            title={sidebarOpen ? 'Hide folders' : 'Show folders'}
          >
            <FolderInput className="h-5 w-5 text-gray-600" />
          </button>
          <div>
            <h1 className="mb-1 text-xl font-semibold text-gray-900 sm:text-2xl">Media Library</h1>
            <p className="text-sm text-gray-600">{filteredAndSorted.length} files</p>
          </div>
        </div>
        <div>
          <input
            ref={fileInputRef}
            type="file"
            multiple
            accept="image/*,video/*,application/pdf,.doc,.docx,.xls,.xlsx"
            className="hidden"
            onChange={(e) => handleUploadFiles(e.target.files)}
          />
          <button
            onClick={() => fileInputRef.current?.click()}
            disabled={uploading}
            className="flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm text-white transition-colors hover:bg-blue-700 disabled:opacity-50"
          >
            {uploading ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Upload className="h-4 w-4" />
            )}
            {uploading ? 'Uploading...' : 'Upload Files'}
          </button>
        </div>
      </div>

      <div className="flex min-h-0 flex-1 gap-4 overflow-hidden">
        {sidebarOpen && (
          <div className="flex w-56 shrink-0 flex-col overflow-hidden rounded-lg border border-gray-200 bg-white">
            <FolderTree
              scope="media"
              selected={folderSel}
              onSelect={(sel) => {
                setFolderSel(sel)
                setSelectedMedia([])
              }}
              totalCount={allData.data?.total}
              uncategorizedCount={uncatData.data?.total}
              onDropItem={handleDropItem}
            />
          </div>
        )}

        <div className="flex min-w-0 flex-1 flex-col">
          <div className="mb-4 rounded-lg border border-gray-200 bg-white">
            <div className="flex items-center justify-between p-3">
              <div className="flex flex-1 items-center gap-3">
                <div className="relative max-w-md flex-1">
                  <Search className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-gray-400" />
                  <input
                    type="text"
                    placeholder="Search media..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="w-full rounded-lg border border-gray-300 py-2 pr-3 pl-9 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                  />
                </div>
                <select
                  value={filterType}
                  onChange={(e) => setFilterType(e.target.value)}
                  className="rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                >
                  <option value="all">All Types</option>
                  <option value="image">Images</option>
                  <option value="video">Videos</option>
                  <option value="document">Documents</option>
                </select>
              </div>
              <div className="flex items-center gap-1 rounded-lg bg-gray-100 p-1">
                <button
                  onClick={() => setViewMode('grid')}
                  className={`rounded p-1.5 transition-colors ${viewMode === 'grid' ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-600 hover:text-gray-900'}`}
                >
                  <Grid3x3 className="h-4 w-4" />
                </button>
                <button
                  onClick={() => setViewMode('list')}
                  className={`rounded p-1.5 transition-colors ${viewMode === 'list' ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-600 hover:text-gray-900'}`}
                >
                  <List className="h-4 w-4" />
                </button>
              </div>
            </div>
          </div>

          {selectedMedia.length > 0 && (
            <div className="mb-4 rounded-lg border border-blue-200 bg-blue-50 p-3">
              <div className="flex items-center justify-between">
                <span className="text-sm text-blue-900">
                  {selectedMedia.length} file{selectedMedia.length !== 1 ? 's' : ''} selected
                </span>
                <div className="flex items-center gap-2">
                  <button
                    onClick={async () => {
                      for (const id of selectedMedia) await deleteMedia(id)
                      setSelectedMedia([])
                    }}
                    className="rounded-lg bg-red-600 px-3 py-1.5 text-sm text-white transition-colors hover:bg-red-700"
                  >
                    Delete Selected
                  </button>
                  <button
                    onClick={() => setSelectedMedia([])}
                    className="rounded-lg border border-gray-300 bg-white px-3 py-1.5 text-sm transition-colors hover:bg-gray-50"
                  >
                    Cancel
                  </button>
                </div>
              </div>
            </div>
          )}

          {filteredAndSorted.length === 0 && !loading ? (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-gray-100">
                <ImageIcon className="h-6 w-6 text-gray-400" />
              </div>
              <h3 className="mb-1 text-sm font-medium text-gray-900">
                {folderSel.type === 'smart' && folderSel.smart === 'uncategorized'
                  ? 'No uncategorized media'
                  : folderSel.type === 'folder'
                    ? 'No media in this folder'
                    : 'No media yet'}
              </h3>
              <p className="text-sm text-gray-500">Upload your first file to get started.</p>
            </div>
          ) : (
            <div className="flex min-h-0 flex-1 gap-4 overflow-hidden">
              <div
                className={`overflow-hidden rounded-lg border border-gray-200 bg-white transition-all duration-200 ${panelOpen ? 'min-w-0 flex-1' : 'w-full'}`}
              >
                {viewMode === 'grid' ? (
                  <div
                    className={`grid h-full auto-rows-min content-start gap-3 overflow-y-auto p-2 sm:gap-4 sm:p-3 ${
                      panelOpen
                        ? 'grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4'
                        : 'grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-8'
                    }`}
                  >
                    {filteredAndSorted.map((item) => {
                      const isActive = activeItem?.id === item.id
                      const hasIssues = !item.altTag || !item.title || item.usedOn?.length === 0
                      const typeLabel = (
                        item.name.includes('.')
                          ? item.name.split('.').pop()!
                          : item.format || item.type || ''
                      )
                        .replace(/^.*\//, '')
                        .toUpperCase()
                      return (
                        <div
                          key={item.id}
                          className={`group relative flex cursor-pointer flex-col overflow-hidden rounded-lg border-2 transition-all ${
                            isActive
                              ? 'border-blue-500 ring-2 ring-blue-200'
                              : selectedMedia.includes(item.id)
                                ? 'border-blue-400 ring-1 ring-blue-100'
                                : 'border-gray-200 hover:border-gray-300'
                          }`}
                          onClick={() => openDetail(item)}
                          draggable
                          onDragStart={(e) => handleDragStart(e, item.id)}
                        >
                          <div className="relative aspect-square w-full overflow-hidden">
                            <div className="flex h-full w-full items-center justify-center bg-gray-100">
                              <MediaPreview item={item} />
                            </div>
                            {hasIssues && (
                              <div
                                className="absolute top-1.5 left-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-yellow-500"
                                title="Needs attention"
                              >
                                <AlertTriangle className="h-3 w-3 text-white" />
                              </div>
                            )}
                            <div
                              className="absolute top-1.5 right-1.5 opacity-0 transition-opacity group-hover:opacity-100"
                              onClick={(e) => handleCheckbox(e, item.id)}
                            >
                              <div
                                className={`flex h-5 w-5 items-center justify-center rounded border-2 transition-colors ${
                                  selectedMedia.includes(item.id)
                                    ? 'border-blue-600 bg-blue-600'
                                    : 'border-gray-400 bg-white/80'
                                }`}
                              >
                                {selectedMedia.includes(item.id) && (
                                  <svg
                                    className="h-3 w-3 text-white"
                                    fill="none"
                                    viewBox="0 0 12 12"
                                  >
                                    <path
                                      d="M10 3L4.5 8.5L2 6"
                                      stroke="currentColor"
                                      strokeWidth="2"
                                      strokeLinecap="round"
                                      strokeLinejoin="round"
                                    />
                                  </svg>
                                )}
                              </div>
                            </div>
                          </div>
                          <div className="flex items-center gap-2 border-t border-gray-200 bg-white px-2 py-1.5">
                            <span
                              className={`mt-0.5 h-2 w-2 shrink-0 self-start rounded-full ${
                                hasIssues ? 'bg-yellow-500' : 'bg-green-500'
                              }`}
                              title={hasIssues ? 'Needs attention' : 'SEO complete'}
                            />
                            <div className="min-w-0 flex-1">
                              <p className="truncate text-xs font-medium text-gray-900">
                                {item.name}
                              </p>
                              <p className="truncate text-xs text-gray-500">
                                {[typeLabel, item.size].filter(Boolean).join(' · ')}
                              </p>
                            </div>
                          </div>
                        </div>
                      )
                    })}
                  </div>
                ) : (
                  <div className="h-full overflow-y-auto">
                    <table className="w-full">
                      <thead className="sticky top-0 border-b border-gray-200 bg-gray-50">
                        <tr>
                          <th className="w-8 px-3 py-2 text-left">
                            <input
                              type="checkbox"
                              checked={
                                selectedMedia.length === filteredAndSorted.length &&
                                filteredAndSorted.length > 0
                              }
                              onChange={handleSelectAll}
                              className="rounded border-gray-300"
                            />
                          </th>
                          <th className="w-6 px-1 py-2"></th>
                          <th className="px-3 py-2 text-left">
                            <SortHeader label="Name" sortKey="name" />
                          </th>
                          <th className="px-3 py-2 text-left">
                            <SortHeader label="Type" sortKey="type" />
                          </th>
                          <th className="px-3 py-2 text-left">
                            <SortHeader label="Size" sortKey="size" />
                          </th>
                          <th className="px-3 py-2 text-left">
                            <SortHeader label="Uploaded" sortKey="date" />
                          </th>
                          <th className="px-3 py-2 text-left text-xs font-medium text-gray-700">
                            Status
                          </th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-gray-200">
                        {filteredAndSorted.map((item) => {
                          const isActive = activeItem?.id === item.id
                          const hasIssues = !item.altTag || !item.title || item.usedOn?.length === 0
                          return (
                            <tr
                              key={item.id}
                              className={`cursor-pointer transition-colors ${isActive ? 'bg-blue-50' : 'hover:bg-gray-50'}`}
                              onClick={() => openDetail(item)}
                              draggable
                              onDragStart={(e) => handleDragStart(e, item.id)}
                            >
                              <td className="px-3 py-2" onClick={(e) => e.stopPropagation()}>
                                <input
                                  type="checkbox"
                                  checked={selectedMedia.includes(item.id)}
                                  onChange={() =>
                                    handleCheckbox(
                                      { stopPropagation: () => {} } as React.MouseEvent,
                                      item.id,
                                    )
                                  }
                                  className="rounded border-gray-300"
                                />
                              </td>
                              <td className="cursor-grab px-1 py-2">
                                <GripVertical className="h-4 w-4 text-gray-300" />
                              </td>
                              <td className="px-3 py-2">
                                <div className="flex items-center gap-3">
                                  <div className="flex h-10 w-10 items-center justify-center overflow-hidden rounded bg-gray-100">
                                    <MediaPreview item={item} />
                                  </div>
                                  <span className="text-sm font-medium text-gray-900">
                                    {item.name}
                                  </span>
                                </div>
                              </td>
                              <td className="px-3 py-2 text-sm text-gray-600">
                                {item.format ?? item.type}
                              </td>
                              <td className="px-3 py-2 text-sm text-gray-600">{item.size}</td>
                              <td className="px-3 py-2 text-sm text-gray-600">{item.date}</td>
                              <td className="px-3 py-2">
                                {hasIssues ? (
                                  <span className="inline-flex items-center gap-1 rounded-full bg-yellow-100 px-2 py-0.5 text-xs font-medium text-yellow-800">
                                    <AlertTriangle className="h-3 w-3" /> Needs attention
                                  </span>
                                ) : (
                                  <span className="inline-flex items-center rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-800">
                                    Complete
                                  </span>
                                )}
                              </td>
                            </tr>
                          )
                        })}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>

              {panelOpen && activeItem && (
                <div className="flex w-80 shrink-0 flex-col overflow-y-auto rounded-lg border border-gray-200 bg-white lg:w-96">
                  <div className="sticky top-0 z-10 flex items-center justify-between border-b border-gray-200 bg-white p-4">
                    <h3 className="truncate text-sm font-semibold text-gray-900">
                      {activeItem.name}
                    </h3>
                    <button
                      onClick={closeDetail}
                      className="rounded p-1 transition-colors hover:bg-gray-100"
                      aria-label="Close panel"
                    >
                      <X className="h-4 w-4 text-gray-500" />
                    </button>
                  </div>

                  <div className="flex-1 overflow-y-auto">
                    <div className="border-b border-gray-200 p-4">
                      <div className="flex aspect-video items-center justify-center overflow-hidden rounded-lg bg-gray-100">
                        {isImageMedia(activeItem) ? (
                          <MediaPreview item={activeItem} />
                        ) : (
                          <ImageIcon className="h-12 w-12 text-gray-300" />
                        )}
                      </div>
                    </div>

                    {issues.length > 0 && (
                      <div className="mx-4 mt-4 rounded-lg border border-yellow-200 bg-yellow-50 p-3">
                        <div className="flex items-start gap-2">
                          <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-yellow-600" />
                          <div>
                            <p className="mb-1 text-xs font-semibold text-yellow-900">
                              {issues.length} issue{issues.length !== 1 ? 's' : ''} found
                            </p>
                            <ul className="space-y-0.5">
                              {issues.map((issue, i) => (
                                <li key={i} className="text-xs text-yellow-800">
                                  • {issue}
                                </li>
                              ))}
                            </ul>
                          </div>
                        </div>
                        <button
                          type="button"
                          onClick={async () => {
                            if (!activeItem.altTag) await handleAiGenerate('alt')
                            if (!activeItem.title) await handleAiGenerate('title')
                            if (activeItem.sizeBytes > 2000000) await handleAiGenerate('optimize')
                          }}
                          className="mt-2 flex w-full items-center justify-center gap-1.5 rounded-lg bg-yellow-600 px-3 py-1.5 text-xs text-white transition-colors hover:bg-yellow-700"
                        >
                          <Sparkles className="h-3.5 w-3.5" />
                          AI Fix All Issues
                        </button>
                      </div>
                    )}

                    <div className="space-y-3 border-b border-gray-200 p-4">
                      <h4 className="text-xs font-semibold tracking-wide text-gray-500 uppercase">
                        File Information
                      </h4>
                      <div className="grid grid-cols-2 gap-3">
                        <div>
                          <div className="mb-0.5 text-xs text-gray-500">Format</div>
                          <div className="text-sm text-gray-900">
                            {activeItem.format ?? 'Unknown'}
                          </div>
                        </div>
                        <div>
                          <div className="mb-0.5 text-xs text-gray-500">File Size</div>
                          <div className="flex items-center gap-1 text-sm text-gray-900">
                            {activeItem.size}
                            {activeItem.sizeBytes > 2000000 && (
                              <span className="text-xs text-yellow-600">(large)</span>
                            )}
                          </div>
                        </div>
                        <div>
                          <div className="mb-0.5 text-xs text-gray-500">Dimensions</div>
                          <div className="text-sm text-gray-900">
                            {activeItem.dimensions ?? '—'}
                          </div>
                        </div>
                        <div>
                          <div className="mb-0.5 text-xs text-gray-500">Uploaded</div>
                          <div className="text-sm text-gray-900">{activeItem.date}</div>
                        </div>
                      </div>

                      <div>
                        <div className="mb-1 text-xs text-gray-500">URL</div>
                        <div className="flex items-center gap-1">
                          <code className="flex-1 truncate rounded border border-gray-200 bg-gray-50 px-2 py-1.5 text-xs text-gray-700">
                            {activeItem.url}
                          </code>
                          <button
                            onClick={handleCopyUrl}
                            className="shrink-0 rounded p-1.5 transition-colors hover:bg-gray-100"
                            title="Copy URL"
                          >
                            <Copy className="h-3.5 w-3.5 text-gray-500" />
                          </button>
                        </div>
                      </div>
                    </div>

                    <div className="space-y-4 border-b border-gray-200 p-4">
                      <h4 className="text-xs font-semibold tracking-wide text-gray-500 uppercase">
                        SEO & Accessibility
                      </h4>

                      <div>
                        <div className="mb-1 flex items-center justify-between">
                          <label className="text-sm font-medium text-gray-700">Alt Tag</label>
                          <button
                            type="button"
                            onClick={() => handleAiGenerate('alt')}
                            disabled={aiGenerating === 'alt'}
                            className="flex items-center gap-1 text-xs text-indigo-600 transition-colors hover:text-indigo-700 disabled:opacity-50"
                          >
                            <Bot className="h-3.5 w-3.5" />
                            {aiGenerating === 'alt' ? 'Generating...' : 'AI Generate'}
                          </button>
                        </div>
                        <textarea
                          value={editAlt}
                          onChange={(e) => setEditAlt(e.target.value)}
                          placeholder="Describe this image for accessibility..."
                          rows={2}
                          className="w-full resize-none rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                        />
                        {!editAlt && (
                          <p className="mt-1 text-xs text-red-500">
                            Required for accessibility and SEO
                          </p>
                        )}
                      </div>

                      <div>
                        <div className="mb-1 flex items-center justify-between">
                          <label className="text-sm font-medium text-gray-700">Title</label>
                          <button
                            type="button"
                            onClick={() => handleAiGenerate('title')}
                            disabled={aiGenerating === 'title'}
                            className="flex items-center gap-1 text-xs text-indigo-600 transition-colors hover:text-indigo-700 disabled:opacity-50"
                          >
                            <Bot className="h-3.5 w-3.5" />
                            {aiGenerating === 'title' ? 'Generating...' : 'AI Generate'}
                          </button>
                        </div>
                        <input
                          type="text"
                          value={editTitle}
                          onChange={(e) => setEditTitle(e.target.value)}
                          placeholder="Image title..."
                          className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                        />
                      </div>

                      <div>
                        <label className="mb-1 block text-sm font-medium text-gray-700">
                          File Name
                        </label>
                        <input
                          type="text"
                          value={editFilename}
                          onChange={(e) => setEditFilename(e.target.value)}
                          className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                        />
                      </div>
                    </div>

                    <div className="border-b border-gray-200 p-4">
                      <h4 className="mb-3 text-xs font-semibold tracking-wide text-gray-500 uppercase">
                        Used On {activeItem.usedOn && `(${activeItem.usedOn.length})`}
                      </h4>
                      {activeItem.usedOn && activeItem.usedOn.length > 0 ? (
                        <div className="space-y-2">
                          {activeItem.usedOn.map((usage, i) => (
                            <button
                              key={i}
                              type="button"
                              onClick={() => onNavigate?.(usage.path)}
                              className="flex w-full items-center gap-2 rounded-lg border border-gray-200 p-2 text-left transition-colors hover:bg-gray-50"
                            >
                              <Link2 className="h-4 w-4 shrink-0 text-gray-400" />
                              <span className="flex-1 truncate text-sm text-gray-900">
                                {usage.page}
                              </span>
                              <ExternalLink className="h-3.5 w-3.5 shrink-0 text-gray-400" />
                            </button>
                          ))}
                        </div>
                      ) : (
                        <div className="rounded-lg border border-orange-200 bg-orange-50 p-3">
                          <div className="flex items-start gap-2">
                            <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-orange-600" />
                            <div>
                              <p className="text-xs font-medium text-orange-900">Orphaned media</p>
                              <p className="mt-0.5 text-xs text-orange-700">
                                This file isn&apos;t used on any page. Consider deleting it to save
                                storage.
                              </p>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>

                    <div className="space-y-3 p-4">
                      <h4 className="text-xs font-semibold tracking-wide text-gray-500 uppercase">
                        AI Optimization
                      </h4>
                      <button
                        type="button"
                        onClick={() => handleAiGenerate('optimize')}
                        disabled={aiGenerating === 'optimize'}
                        className="flex w-full items-center gap-2 rounded-lg border border-indigo-200 bg-indigo-50 p-3 text-left transition-colors hover:bg-indigo-100 disabled:opacity-50"
                      >
                        <Sparkles
                          className={`h-5 w-5 shrink-0 text-indigo-600 ${aiGenerating === 'optimize' ? 'animate-spin' : ''}`}
                        />
                        <div className="flex-1">
                          <div className="text-sm font-medium text-indigo-900">
                            {aiGenerating === 'optimize' ? 'Optimizing...' : 'Optimize Image'}
                          </div>
                          <div className="mt-0.5 text-xs text-indigo-700">
                            Compress and convert to modern format (WebP/AVIF)
                          </div>
                        </div>
                      </button>
                      <button
                        type="button"
                        className="flex w-full items-center gap-2 rounded-lg border border-gray-200 p-3 text-left transition-colors hover:bg-gray-50"
                      >
                        <Bot className="h-5 w-5 shrink-0 text-gray-500" />
                        <div className="flex-1">
                          <div className="text-sm font-medium text-gray-900">
                            AI Content Analysis
                          </div>
                          <div className="mt-0.5 text-xs text-gray-600">
                            Detect objects, faces, text, and suggest categories
                          </div>
                        </div>
                      </button>
                    </div>
                  </div>

                  <div className="sticky bottom-0 flex items-center gap-2 border-t border-gray-200 bg-white p-4">
                    <button
                      type="button"
                      onClick={handleSaveDetails}
                      disabled={saving}
                      className="flex flex-1 items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm text-white transition-colors hover:bg-blue-700 disabled:opacity-50"
                    >
                      {saving && <Loader2 className="h-4 w-4 animate-spin" />}
                      {saving ? 'Saving...' : 'Save Changes'}
                    </button>
                    <button
                      type="button"
                      className="rounded-lg p-2 transition-colors hover:bg-gray-100"
                      title="Download"
                    >
                      <Download className="h-4 w-4 text-gray-600" />
                    </button>
                    <button
                      type="button"
                      onClick={() => deleteMedia(activeItem.id)}
                      className="rounded-lg p-2 transition-colors hover:bg-gray-100"
                      title="Delete"
                    >
                      <Trash2 className="h-4 w-4 text-red-600" />
                    </button>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
