'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="text-foreground hover:text-foreground flex items-center gap-1 text-xs font-medium transition-colors"
      >
        {label}
        {active ? (
          sortConfig!.direction === 'asc' ? (
            <ArrowUp className="h-3 w-3" />
          ) : (
            <ArrowDown className="h-3 w-3" />
          )
        ) : (
          <ArrowUpDown className="text-muted-foreground h-3 w-3" />
        )}
      </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="text-primary h-6 w-6 animate-spin" />
      </div>
    )
  }

  return (
    <div className="flex h-full flex-col p-3 pr-6 sm:p-4 sm:pr-8">
      {error && (
        <div className="border-destructive/30 bg-destructive/10 mb-4 flex items-center gap-3 rounded-lg border p-3">
          <AlertTriangle className="text-destructive h-5 w-5 shrink-0" />
          <span className="text-destructive flex-1 text-sm">{error}</span>
          <button
            onClick={refetch}
            className="border-destructive/40 text-destructive hover:bg-destructive/15 rounded-lg border px-3 py-1 text-sm transition-colors"
          >
            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="hover:bg-muted rounded-lg p-1.5 transition-colors"
            title={sidebarOpen ? 'Hide folders' : 'Show folders'}
          >
            <FolderInput className="text-muted-foreground h-5 w-5" />
          </button>
          <div>
            <h1 className="text-foreground mb-1 text-xl font-medium sm:text-2xl">Media Library</h1>
            <p className="text-muted-foreground text-sm">{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="bg-primary text-primary-foreground hover:bg-primary/90 flex items-center gap-2 rounded-lg px-4 py-2 text-sm transition-colors 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="border-border bg-card flex w-56 shrink-0 flex-col overflow-hidden rounded-lg border">
            <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="border-border bg-card mb-4 rounded-lg border">
            <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="text-muted-foreground absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2" />
                  <input
                    type="text"
                    placeholder="Search media..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="border-input focus:ring-ring w-full rounded-lg border py-2 pr-3 pl-9 text-sm focus:ring-2 focus:outline-none"
                  />
                </div>
                <select
                  value={filterType}
                  onChange={(e) => setFilterType(e.target.value)}
                  className="border-input focus:ring-ring rounded-lg border px-3 py-2 text-sm focus:ring-2 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="bg-muted flex items-center gap-1 rounded-lg p-1">
                <button
                  onClick={() => setViewMode('grid')}
                  className={`rounded p-1.5 transition-colors ${viewMode === 'grid' ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}
                >
                  <Grid3x3 className="h-4 w-4" />
                </button>
                <button
                  onClick={() => setViewMode('list')}
                  className={`rounded p-1.5 transition-colors ${viewMode === 'list' ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}
                >
                  <List className="h-4 w-4" />
                </button>
              </div>
            </div>
          </div>

          {selectedMedia.length > 0 && (
            <div className="border-primary/30 bg-primary/10 mb-4 rounded-lg border p-3">
              <div className="flex items-center justify-between">
                <span className="text-primary text-sm">
                  {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="bg-destructive text-destructive-foreground hover:bg-destructive/90 rounded-lg px-3 py-1.5 text-sm transition-colors"
                  >
                    Delete Selected
                  </button>
                  <button
                    onClick={() => setSelectedMedia([])}
                    className="border-input bg-card hover:bg-muted rounded-lg border px-3 py-1.5 text-sm transition-colors"
                  >
                    Cancel
                  </button>
                </div>
              </div>
            </div>
          )}

          {filteredAndSorted.length === 0 && !loading ? (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <div className="bg-muted mb-4 flex h-12 w-12 items-center justify-center rounded-full">
                <ImageIcon className="text-muted-foreground h-6 w-6" />
              </div>
              <h3 className="text-foreground mb-1 text-sm font-medium">
                {folderSel.type === 'smart' && folderSel.smart === 'uncategorized'
                  ? 'No uncategorized media'
                  : folderSel.type === 'folder'
                    ? 'No media in this folder'
                    : 'No media yet'}
              </h3>
              <p className="text-muted-foreground text-sm">
                Upload your first file to get started.
              </p>
            </div>
          ) : (
            <div className="flex min-h-0 flex-1 gap-4 overflow-hidden">
              <div
                className={`border-border bg-card overflow-hidden rounded-lg border 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-primary ring-primary/30 ring-2'
                              : selectedMedia.includes(item.id)
                                ? 'border-primary/60 ring-primary/20 ring-1'
                                : 'border-border hover:border-input'
                          }`}
                          onClick={() => openDetail(item)}
                          draggable
                          onDragStart={(e) => handleDragStart(e, item.id)}
                        >
                          <div className="relative aspect-square w-full overflow-hidden">
                            <div className="bg-muted flex h-full w-full items-center justify-center">
                              <MediaPreview item={item} />
                            </div>
                            {hasIssues && (
                              <div
                                className="bg-warning absolute top-1.5 left-1.5 flex h-5 w-5 items-center justify-center rounded-full"
                                title="Needs attention"
                              >
                                <AlertTriangle className="text-warning-foreground h-3 w-3" />
                              </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-primary bg-primary'
                                    : 'border-input bg-card/80'
                                }`}
                              >
                                {selectedMedia.includes(item.id) && (
                                  <svg
                                    className="text-primary-foreground h-3 w-3"
                                    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="border-border bg-card flex items-center gap-2 border-t px-2 py-1.5">
                            <span
                              className={`mt-0.5 h-2 w-2 shrink-0 self-start rounded-full ${
                                hasIssues ? 'bg-warning' : 'bg-success'
                              }`}
                              title={hasIssues ? 'Needs attention' : 'SEO complete'}
                            />
                            <div className="min-w-0 flex-1">
                              <p className="text-foreground truncate text-xs font-medium">
                                {item.name}
                              </p>
                              <p className="text-muted-foreground truncate text-xs">
                                {[typeLabel, item.size].filter(Boolean).join(' · ')}
                              </p>
                            </div>
                          </div>
                        </div>
                      )
                    })}
                  </div>
                ) : (
                  <div className="h-full overflow-y-auto">
                    <table className="w-full">
                      <thead className="border-border bg-muted sticky top-0 border-b">
                        <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="border-input rounded"
                            />
                          </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="text-foreground px-3 py-2 text-left text-xs font-medium">
                            Status
                          </th>
                        </tr>
                      </thead>
                      <tbody className="divide-border divide-y">
                        {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-primary/10' : 'hover:bg-muted'}`}
                              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="border-input rounded"
                                />
                              </td>
                              <td className="cursor-grab px-1 py-2">
                                <GripVertical className="text-muted-foreground h-4 w-4" />
                              </td>
                              <td className="px-3 py-2">
                                <div className="flex items-center gap-3">
                                  <div className="bg-muted flex h-10 w-10 items-center justify-center overflow-hidden rounded">
                                    <MediaPreview item={item} />
                                  </div>
                                  <span className="text-foreground text-sm font-medium">
                                    {item.name}
                                  </span>
                                </div>
                              </td>
                              <td className="text-muted-foreground px-3 py-2 text-sm">
                                {item.format ?? item.type}
                              </td>
                              <td className="text-muted-foreground px-3 py-2 text-sm">
                                {item.size}
                              </td>
                              <td className="text-muted-foreground px-3 py-2 text-sm">
                                {item.date}
                              </td>
                              <td className="px-3 py-2">
                                {hasIssues ? (
                                  <span className="bg-warning/15 text-warning inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium">
                                    <AlertTriangle className="h-3 w-3" /> Needs attention
                                  </span>
                                ) : (
                                  <span className="bg-success/15 text-success inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium">
                                    Complete
                                  </span>
                                )}
                              </td>
                            </tr>
                          )
                        })}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>

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

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

                    {issues.length > 0 && (
                      <div className="border-warning/30 bg-warning/10 mx-4 mt-4 rounded-lg border p-3">
                        <div className="flex items-start gap-2">
                          <AlertTriangle className="text-warning mt-0.5 h-4 w-4 shrink-0" />
                          <div>
                            <p className="text-warning mb-1 text-xs font-medium">
                              {issues.length} issue{issues.length !== 1 ? 's' : ''} found
                            </p>
                            <ul className="space-y-0.5">
                              {issues.map((issue, i) => (
                                <li key={i} className="text-warning text-xs">
                                  • {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="bg-warning text-warning-foreground hover:bg-warning/90 mt-2 flex w-full items-center justify-center gap-1.5 rounded-lg px-3 py-1.5 text-xs transition-colors"
                        >
                          <Sparkles className="h-3.5 w-3.5" />
                          AI Fix All Issues
                        </button>
                      </div>
                    )}

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

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

                    <div className="border-border space-y-4 border-b p-4">
                      <h4 className="text-muted-foreground text-xs font-medium tracking-wide uppercase">
                        SEO & Accessibility
                      </h4>

                      <div>
                        <div className="mb-1 flex items-center justify-between">
                          <label className="text-foreground text-sm font-medium">Alt Tag</label>
                          <button
                            type="button"
                            onClick={() => handleAiGenerate('alt')}
                            disabled={aiGenerating === 'alt'}
                            className="text-primary hover:text-primary/80 flex items-center gap-1 text-xs transition-colors 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="border-input focus:ring-ring w-full resize-none rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
                        />
                        {!editAlt && (
                          <p className="text-destructive mt-1 text-xs">
                            Required for accessibility and SEO
                          </p>
                        )}
                      </div>

                      <div>
                        <div className="mb-1 flex items-center justify-between">
                          <label className="text-foreground text-sm font-medium">Title</label>
                          <button
                            type="button"
                            onClick={() => handleAiGenerate('title')}
                            disabled={aiGenerating === 'title'}
                            className="text-primary hover:text-primary/80 flex items-center gap-1 text-xs transition-colors 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="border-input focus:ring-ring w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
                        />
                      </div>

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

                    <div className="border-border border-b p-4">
                      <h4 className="text-muted-foreground mb-3 text-xs font-medium tracking-wide 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="border-border hover:bg-muted flex w-full items-center gap-2 rounded-lg border p-2 text-left transition-colors"
                            >
                              <Link2 className="text-muted-foreground h-4 w-4 shrink-0" />
                              <span className="text-foreground flex-1 truncate text-sm">
                                {usage.page}
                              </span>
                              <ExternalLink className="text-muted-foreground h-3.5 w-3.5 shrink-0" />
                            </button>
                          ))}
                        </div>
                      ) : (
                        <div className="border-warning/30 bg-warning/10 rounded-lg border p-3">
                          <div className="flex items-start gap-2">
                            <AlertTriangle className="text-warning mt-0.5 h-4 w-4 shrink-0" />
                            <div>
                              <p className="text-warning text-xs font-medium">Orphaned media</p>
                              <p className="text-warning mt-0.5 text-xs">
                                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-muted-foreground text-xs font-medium tracking-wide uppercase">
                        AI Optimization
                      </h4>
                      <button
                        type="button"
                        onClick={() => handleAiGenerate('optimize')}
                        disabled={aiGenerating === 'optimize'}
                        className="border-primary/30 bg-primary/10 hover:bg-primary/15 flex w-full items-center gap-2 rounded-lg border p-3 text-left transition-colors disabled:opacity-50"
                      >
                        <Sparkles
                          className={`text-primary h-5 w-5 shrink-0 ${aiGenerating === 'optimize' ? 'animate-spin' : ''}`}
                        />
                        <div className="flex-1">
                          <div className="text-primary text-sm font-medium">
                            {aiGenerating === 'optimize' ? 'Optimizing...' : 'Optimize Image'}
                          </div>
                          <div className="text-primary mt-0.5 text-xs">
                            Compress and convert to modern format (WebP/AVIF)
                          </div>
                        </div>
                      </button>
                      <button
                        type="button"
                        className="border-border hover:bg-muted flex w-full items-center gap-2 rounded-lg border p-3 text-left transition-colors"
                      >
                        <Bot className="text-muted-foreground h-5 w-5 shrink-0" />
                        <div className="flex-1">
                          <div className="text-foreground text-sm font-medium">
                            AI Content Analysis
                          </div>
                          <div className="text-muted-foreground mt-0.5 text-xs">
                            Detect objects, faces, text, and suggest categories
                          </div>
                        </div>
                      </button>
                    </div>
                  </div>

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