import { useState, useEffect, useCallback } from 'react'
import { useSuggestions } from '../hooks/useSuggestions'
import { useModels } from '../hooks/useModels'
import { motion, AnimatePresence } from 'framer-motion'
import {
  Search, ChevronLeft, ChevronRight, CheckCircle2, Clock,
  FileText, Loader2, Save, RefreshCw, Trash2, Sparkles, Cloud, CloudOff,
} from 'lucide-react'
import axios from 'axios'

const API_BASE = import.meta.env.VITE_API_URL || '/api'

const INPUT_CLASS =
  'w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-gray-200 ' +
  'placeholder-gray-600 focus:outline-none focus:border-purple-500/50 transition-colors'

const STATUS_COLORS = {
  unreviewed: 'text-amber-400 bg-amber-400/10 border-amber-400/30',
  reviewed:   'text-green-400 bg-green-400/10 border-green-400/30',
}

function StatusBadge({ status }) {
  const Icon = status === 'reviewed' ? CheckCircle2 : Clock
  return (
    <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs border ${STATUS_COLORS[status] || 'text-gray-400'}`}>
      <Icon className="w-3 h-3" />
      {status}
    </span>
  )
}

// A job is synced "in its most recent state" when it was pushed to Qdrant at or
// after its last update. `updated_at` is bumped by a DB trigger on every change,
// so any edit after a sync makes the job stale until it's re-synced.
function isSynced(job) {
  if (!job.qdrant_synced_at) return false
  if (!job.updated_at) return true
  return new Date(job.qdrant_synced_at).getTime() >= new Date(job.updated_at).getTime()
}

function SyncBadge({ job }) {
  const synced = isSynced(job)
  const Icon = synced ? Cloud : CloudOff
  const title = synced
    ? 'Synced with Qdrant'
    : job.qdrant_synced_at
      ? 'Changed since last Qdrant sync — needs re-sync'
      : 'Never synced with Qdrant'
  return (
    <span
      title={title}
      className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs border ${
        synced
          ? 'text-green-400 bg-green-400/10 border-green-400/30'
          : 'text-orange-400 bg-orange-400/10 border-orange-400/30'
      }`}
    >
      <Icon className="w-3 h-3" />
      {synced ? 'Synced' : 'Not synced'}
    </span>
  )
}

// ─────────────────────────────────────────────────────────────
// Full-screen Job Detail
// ─────────────────────────────────────────────────────────────
function JobDetail({ jobId, onClose, onReviewed, onDeleted, suggestions = {} }) {
  const { models } = useModels()
  const [job, setJob] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  const [describeModel, setDescribeModel] = useState('')
  const [generatingDescribe, setGeneratingDescribe] = useState(false)

  const [editedText, setEditedText]         = useState('')
  const [editDescribeText, setEditDescribeText] = useState('')
  const [editFreeformText, setEditFreeformText] = useState('')
  const [activeTab, setActiveTab]           = useState('ocr')
  const [editAuthor, setEditAuthor]         = useState('')
  const [editBook, setEditBook]             = useState('')
  const [editChapter, setEditChapter]       = useState('')
  const [editPage, setEditPage]             = useState('')
  const [reviewerName, setReviewerName]     = useState('')

  const [submitting, setSubmitting] = useState(false)
  const [saveResult, setSaveResult] = useState(null)
  const [confirmDelete, setConfirmDelete] = useState(false)
  const [deleting, setDeleting] = useState(false)
  const [togglingStatus, setTogglingStatus] = useState(false)

  useEffect(() => {
    let cancelled = false
    setLoading(true)
    setError(null)
    setSaveResult(null)

    axios.get(`${API_BASE}/jobs/${jobId}`)
      .then(res => {
        if (!cancelled) {
          const d = res.data
          setJob(d)
          setEditedText(d.reviewed_text ?? d.ocr_text ?? '')
          setEditDescribeText(d.describe_text ?? '')
          setEditFreeformText(d.freeform_text ?? '')
          setEditAuthor(d.author || '')
          setEditBook(d.book || '')
          setEditChapter(d.chapter || '')
          setEditPage(d.page || '')
          setReviewerName(d.reviewer_name || '')
          // Default to the OCR tab when there's OCR text, otherwise Description
          if (d.reviewed_text || d.ocr_text) setActiveTab('ocr')
          else setActiveTab('describe')
        }
      })
      .catch(err => {
        if (!cancelled) setError(err.response?.data?.detail || err.message)
      })
      .finally(() => { if (!cancelled) setLoading(false) })

    return () => { cancelled = true }
  }, [jobId])

  // Default the Describe model to the job's original model (if available) or the registry default
  useEffect(() => {
    if (!describeModel && models.length > 0) {
      const def = models.find(m => m.default) || models[0]
      const fromJob = job?.ocr_model && models.some(m => m.id === job.ocr_model) ? job.ocr_model : null
      setDescribeModel(fromJob || def.id)
    }
  }, [models, job, describeModel])

  const handleGenerateDescribe = async () => {
    setGeneratingDescribe(true)
    setSaveResult(null)
    try {
      const res = await axios.post(`${API_BASE}/jobs/${jobId}/describe`, {
        model: describeModel || null,
      })
      setJob(res.data)
      setEditDescribeText(res.data.describe_text || '')
      onReviewed(res.data)
    } catch (err) {
      setSaveResult({ success: false, error: err.response?.data?.detail || err.message })
    } finally {
      setGeneratingDescribe(false)
    }
  }

  const handleSave = async () => {
    if (!reviewerName.trim()) {
      setSaveResult({ success: false, error: 'Reviewer name is required.' })
      return
    }
    setSubmitting(true)
    setSaveResult(null)
    try {
      const res = await axios.put(`${API_BASE}/jobs/${jobId}/review`, {
        reviewed_text: editedText,
        reviewer_name: reviewerName.trim(),
        author: editAuthor,
        book: editBook,
        chapter: editChapter,
        page: editPage,
        describe_text: editDescribeText || null,
        freeform_text: editFreeformText || null,
      })
      setJob(res.data)
      setSaveResult({ success: true })
      onReviewed(res.data)
    } catch (err) {
      setSaveResult({ success: false, error: err.response?.data?.detail || err.message })
    } finally {
      setSubmitting(false)
    }
  }

  const handleToggleStatus = async () => {
    // Marking reviewed accepts BOTH the reviewed document text and the description,
    // so it goes through the full review save (not a status-only flip).
    if (!isReviewed) {
      setTogglingStatus(true)
      try {
        await handleSave()
      } finally {
        setTogglingStatus(false)
      }
      return
    }

    // Reverting to unreviewed preserves the saved reviewed text and description.
    setTogglingStatus(true)
    setSaveResult(null)
    try {
      const res = await axios.put(`${API_BASE}/jobs/${jobId}/status`, {
        status: 'unreviewed',
        reviewer_name: reviewerName.trim() || null,
      })
      setJob(res.data)
      setReviewerName(res.data.reviewer_name || '')
      onReviewed(res.data)
    } catch (err) {
      setSaveResult({ success: false, error: err.response?.data?.detail || err.message })
    } finally {
      setTogglingStatus(false)
    }
  }

  const handleDelete = async () => {
    setDeleting(true)
    try {
      await axios.delete(`${API_BASE}/jobs/${jobId}`)
      onDeleted(jobId)
    } catch (err) {
      setSaveResult({ success: false, error: err.response?.data?.detail || err.message })
      setConfirmDelete(false)
    } finally {
      setDeleting(false)
    }
  }

  const isReviewed = job?.status === 'reviewed'

  return (
    <motion.div
      key={jobId}
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -20 }}
      className="flex flex-col gap-4"
    >
      {/* Top bar */}
      <div className="flex items-center gap-4 flex-shrink-0">
        <motion.button
          onClick={onClose}
          className="flex items-center gap-2 glass glass-hover px-4 py-2 rounded-xl text-sm text-gray-300"
          whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.98 }}
        >
          <ChevronLeft className="w-4 h-4" />
          Back to results
        </motion.button>
        {job && (
          <>
            <StatusBadge status={job.status} />
            <SyncBadge job={job} />
            <motion.button
              onClick={handleToggleStatus}
              disabled={togglingStatus}
              title={isReviewed ? 'Revert to unreviewed' : 'Mark as reviewed'}
              className={`flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors disabled:opacity-50 ${
                isReviewed
                  ? 'glass glass-hover text-amber-400 hover:bg-amber-500/10'
                  : 'glass glass-hover text-green-400 hover:bg-green-500/10'
              }`}
              whileHover={!togglingStatus ? { scale: 1.02 } : {}}
              whileTap={!togglingStatus ? { scale: 0.98 } : {}}
            >
              {togglingStatus ? (
                <Loader2 className="w-3.5 h-3.5 animate-spin" />
              ) : isReviewed ? (
                <Clock className="w-3.5 h-3.5" />
              ) : (
                <CheckCircle2 className="w-3.5 h-3.5" />
              )}
              {isReviewed ? 'Mark Unreviewed' : 'Mark Reviewed'}
            </motion.button>
            <span className="text-xs text-gray-500 font-mono hidden sm:block">{job.id}</span>
          </>
        )}
        <div className="ml-auto flex items-center gap-2">
          {confirmDelete ? (
            <>
              <span className="text-xs text-red-400">Delete this job permanently?</span>
              <motion.button
                onClick={handleDelete}
                disabled={deleting}
                className="flex items-center gap-1 px-3 py-2 rounded-xl text-sm font-medium bg-red-600 hover:bg-red-500 disabled:opacity-50"
                whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.98 }}
              >
                {deleting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
                Confirm
              </motion.button>
              <motion.button
                onClick={() => setConfirmDelete(false)}
                className="px-3 py-2 rounded-xl text-sm glass glass-hover text-gray-300"
                whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.98 }}
              >
                Cancel
              </motion.button>
            </>
          ) : (
            <motion.button
              onClick={() => setConfirmDelete(true)}
              className="flex items-center gap-2 px-3 py-2 rounded-xl text-sm glass glass-hover text-red-400 hover:bg-red-500/10"
              whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.98 }}
            >
              <Trash2 className="w-4 h-4" />
              Delete
            </motion.button>
          )}
        </div>
      </div>

      {loading && (
        <div className="flex-1 flex items-center justify-center">
          <Loader2 className="w-8 h-8 animate-spin text-purple-400" />
        </div>
      )}

      {error && (
        <div className="glass p-4 rounded-xl border-red-500/30 bg-red-500/10 flex-shrink-0">
          <p className="text-sm text-red-400">{error}</p>
        </div>
      )}

      {job && !loading && (
        <>
          {/* Image + Text */}
          <div className="grid gap-6" style={{ gridTemplateColumns: '1fr 1fr', height: '130vh' }}>
            <div className="glass rounded-2xl overflow-hidden flex items-center justify-center bg-black/20 h-full">
              {(job.original_filename || '').toLowerCase().endsWith('.pdf') ? (
                <object
                  data={`${API_BASE}/jobs/${job.id}/image`}
                  type="application/pdf"
                  className="w-full h-full"
                >
                  <div className="flex items-center justify-center h-full">
                    <p className="text-gray-500 text-sm">PDF preview unavailable</p>
                  </div>
                </object>
              ) : (
                <img
                  src={`${API_BASE}/jobs/${job.id}/image`}
                  alt="Job source"
                  className="w-full h-full object-contain"
                  onError={e => { e.target.style.display = 'none' }}
                />
              )}
            </div>
            <div className="glass rounded-2xl p-4 flex flex-col h-full">
              {/* Tabs — only show tabs that have content */}
              {(() => {
                const tabs = [
                  job.ocr_text || job.reviewed_text ? { id: 'ocr', label: 'OCR Text' } : null,
                  { id: 'describe', label: 'Description' },
                ].filter(Boolean)
                return tabs.length > 1 ? (
                  <div className="flex gap-1 mb-3 flex-shrink-0">
                    {tabs.map(t => (
                      <button
                        key={t.id}
                        onClick={() => setActiveTab(t.id)}
                        className={`px-3 py-1 rounded-lg text-xs font-medium transition-colors ${
                          activeTab === t.id
                            ? 'bg-purple-600 text-white'
                            : 'bg-white/5 text-gray-400 hover:bg-white/10'
                        }`}
                      >
                        {t.label}
                      </button>
                    ))}
                  </div>
                ) : null
              })()}

              <p className="text-xs text-gray-400 mb-2 flex-shrink-0">
                {{ ocr: isReviewed ? 'Reviewed Text' : 'OCR Text', describe: 'Description' }[activeTab]}
                <span className="text-purple-400 ml-1">(editable)</span>
              </p>

              {activeTab === 'ocr' && (
                <>
                  <textarea
                    value={editedText}
                    onChange={e => setEditedText(e.target.value)}
                    className="flex-1 w-full bg-transparent text-sm text-gray-200 font-mono resize-none focus:outline-none min-h-0"
                    placeholder="OCR text..."
                  />
                  {isReviewed && job.ocr_text && (
                    <details className="flex-shrink-0 mt-2 border-t border-white/10 pt-2">
                      <summary className="cursor-pointer text-xs text-gray-500 hover:text-gray-400 transition-colors">
                        Original OCR Text
                      </summary>
                      <pre className="text-xs text-gray-600 whitespace-pre-wrap font-mono mt-1 max-h-28 overflow-y-auto">
                        {job.ocr_text}
                      </pre>
                    </details>
                  )}
                </>
              )}
              {activeTab === 'describe' && (
                <>
                  <div className="flex items-center gap-2 mb-2 flex-shrink-0">
                    <select
                      value={describeModel}
                      onChange={e => setDescribeModel(e.target.value)}
                      disabled={generatingDescribe || models.length === 0}
                      className="bg-white/5 border border-white/10 rounded-lg px-2 py-1.5 text-xs text-gray-200 focus:outline-none focus:border-purple-500/50"
                    >
                      {models.length === 0 && <option value="">No models</option>}
                      {models.map(m => (
                        <option key={m.id} value={m.id}>{m.label}{m.default ? ' (default)' : ''}</option>
                      ))}
                    </select>
                    <motion.button
                      onClick={handleGenerateDescribe}
                      disabled={generatingDescribe || !describeModel}
                      className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all ${
                        generatingDescribe || !describeModel
                          ? 'opacity-50 cursor-not-allowed bg-white/5'
                          : 'bg-gradient-to-r from-violet-600 to-purple-600 hover:from-violet-500 hover:to-purple-500'
                      }`}
                      whileHover={!generatingDescribe && describeModel ? { scale: 1.02 } : {}}
                      whileTap={!generatingDescribe && describeModel ? { scale: 0.98 } : {}}
                      title="Run Describe on this job's image and save it"
                    >
                      {generatingDescribe
                        ? <><Loader2 className="w-3.5 h-3.5 animate-spin" /> Generating…</>
                        : <><Sparkles className="w-3.5 h-3.5" /> Generate Description</>}
                    </motion.button>
                  </div>
                  <textarea
                    value={editDescribeText}
                    onChange={e => setEditDescribeText(e.target.value)}
                    className="flex-1 w-full bg-transparent text-sm text-gray-200 font-mono resize-none focus:outline-none min-h-0"
                    placeholder="No description yet — pick a model and click Generate Description, or type one here."
                  />
                </>
              )}
            </div>
          </div>

          {/* Metadata + reviewer row */}
          <div className="glass p-4 rounded-2xl flex-shrink-0">
            <datalist id="jd-authors">
              {(suggestions.authors || []).map(a => <option key={a} value={a} />)}
            </datalist>
            <datalist id="jd-books">
              {(suggestions.books || []).map(b => <option key={b} value={b} />)}
            </datalist>
            <datalist id="jd-chapters">
              {(suggestions.chapters || []).map(c => <option key={c} value={c} />)}
            </datalist>
            <datalist id="jd-reviewers">
              {(suggestions.reviewers || []).map(r => <option key={r} value={r} />)}
            </datalist>
            <div className="grid grid-cols-6 gap-4">
              <div>
                <label className="text-xs text-gray-400 mb-1 block">Author</label>
                <input type="text" list="jd-authors" value={editAuthor} onChange={e => setEditAuthor(e.target.value)} placeholder="Author" className={INPUT_CLASS} />
              </div>
              <div>
                <label className="text-xs text-gray-400 mb-1 block">Book</label>
                <input type="text" list="jd-books" value={editBook} onChange={e => setEditBook(e.target.value)} placeholder="Book title" className={INPUT_CLASS} />
              </div>
              <div>
                <label className="text-xs text-gray-400 mb-1 block">Chapter</label>
                <input type="text" list="jd-chapters" value={editChapter} onChange={e => setEditChapter(e.target.value)} placeholder="Chapter" className={INPUT_CLASS} />
              </div>
              <div>
                <label className="text-xs text-gray-400 mb-1 block">Page</label>
                <input type="text" value={editPage} onChange={e => setEditPage(e.target.value)} placeholder="Page" className={INPUT_CLASS} />
              </div>
              <div>
                <label className="text-xs text-gray-400 mb-1 block">Reviewer</label>
                <input type="text" list="jd-reviewers" value={reviewerName} onChange={e => setReviewerName(e.target.value)} placeholder="Your name" className={INPUT_CLASS} />
              </div>
              <div className="flex flex-col justify-end">
                <motion.button
                  onClick={handleSave}
                  disabled={submitting || !reviewerName.trim()}
                  className={`w-full flex items-center justify-center gap-2 px-4 py-2 rounded-lg font-medium text-sm transition-all ${
                    submitting || !reviewerName.trim()
                      ? 'opacity-50 cursor-not-allowed bg-white/5'
                      : isReviewed
                        ? 'bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500'
                        : 'bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-500 hover:to-emerald-500'
                  }`}
                  whileHover={!submitting && reviewerName.trim() ? { scale: 1.02 } : {}}
                  whileTap={!submitting && reviewerName.trim() ? { scale: 0.98 } : {}}
                >
                  {submitting ? (
                    <><Loader2 className="w-4 h-4 animate-spin" /> Saving...</>
                  ) : isReviewed ? (
                    <><Save className="w-4 h-4" /> Save Changes</>
                  ) : (
                    <><CheckCircle2 className="w-4 h-4" /> Mark Reviewed</>
                  )}
                </motion.button>
              </div>
            </div>

            {!isReviewed && (
              <p className="text-xs text-gray-500 mt-2">
                Marking reviewed accepts both the reviewed document text and the description.
              </p>
            )}

            {saveResult && (
              <motion.div
                initial={{ opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }}
                className={`mt-3 p-2 rounded-lg text-xs ${saveResult.success ? 'bg-green-500/10 text-green-400' : 'bg-red-500/10 text-red-400'}`}
              >
                {saveResult.success
                  ? (isReviewed ? 'Changes saved!' : 'Job marked as reviewed!')
                  : saveResult.error}
              </motion.div>
            )}

            {/* Read-only info row */}
            <div className="flex gap-6 mt-3 pt-3 border-t border-white/10">
              {job.submitted_at && (
                <span className="text-xs text-gray-500">Submitted: {new Date(job.submitted_at).toLocaleString()}</span>
              )}
              {isReviewed && job.reviewed_at && (
                <span className="text-xs text-gray-500">Last reviewed: {new Date(job.reviewed_at).toLocaleString()}</span>
              )}
              {job.mode && <span className="text-xs text-gray-500">Mode: {job.mode}</span>}
              {job.ocr_model && <span className="text-xs text-gray-500">Model: {job.ocr_model}</span>}
            </div>
          </div>
        </>
      )}
    </motion.div>
  )
}

// ─────────────────────────────────────────────────────────────
// Search / List view
// ─────────────────────────────────────────────────────────────
export default function JobsPanel() {
  const suggestions = useSuggestions()
  const [search, setSearch] = useState('')
  const [filterStatus, setFilterStatus] = useState('')
  const [filterAuthor, setFilterAuthor] = useState('')
  const [filterBook, setFilterBook] = useState('')
  const [jobs, setJobs] = useState([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(0)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)
  const [selectedJobId, setSelectedJobId] = useState(null)

  const LIMIT = 20

  const fetchJobs = useCallback(async (pageNum = 0) => {
    setLoading(true)
    setError(null)
    try {
      const params = new URLSearchParams()
      if (search.trim()) params.set('search', search.trim())
      if (filterStatus) params.set('status', filterStatus)
      if (filterAuthor.trim()) params.set('author', filterAuthor.trim())
      if (filterBook.trim()) params.set('book', filterBook.trim())
      params.set('limit', LIMIT)
      params.set('offset', pageNum * LIMIT)

      const res = await axios.get(`${API_BASE}/jobs?${params}`)
      setJobs(res.data.jobs)
      setTotal(res.data.total)
      setPage(pageNum)
    } catch (err) {
      setError(err.response?.data?.detail || err.message)
    } finally {
      setLoading(false)
    }
  }, [search, filterStatus, filterAuthor, filterBook])

  useEffect(() => { fetchJobs(0) }, []) // eslint-disable-line react-hooks/exhaustive-deps

  const handleReviewed = (updatedJob) => {
    setJobs(prev => prev.map(j => j.id === updatedJob.id ? { ...j, ...updatedJob } : j))
  }

  const totalPages = Math.ceil(total / LIMIT)

  // When a job is selected show full-screen detail
  if (selectedJobId) {
    return (
      <AnimatePresence mode="wait">
        <JobDetail
          key={selectedJobId}
          jobId={selectedJobId}
          onClose={() => setSelectedJobId(null)}
          onReviewed={handleReviewed}
          onDeleted={(id) => {
            setJobs(prev => prev.filter(j => j.id !== id))
            setTotal(prev => prev - 1)
            setSelectedJobId(null)
          }}
          suggestions={suggestions}
        />
      </AnimatePresence>
    )
  }

  return (
    <motion.div
      key="job_list"
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -20 }}
      className="space-y-4"
    >
      {/* Search form */}
      <div className="glass p-4 rounded-2xl space-y-3">
        <form onSubmit={e => { e.preventDefault(); fetchJobs(0) }} className="flex gap-2">
          <input
            type="text"
            value={search}
            onChange={e => setSearch(e.target.value)}
            placeholder="Search all fields..."
            className={`${INPUT_CLASS} flex-1`}
          />
          <motion.button
            type="submit"
            className="flex items-center gap-2 px-4 py-2 rounded-lg bg-gradient-to-r from-purple-600 to-cyan-600 text-sm font-medium"
            whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.98 }}
          >
            <Search className="w-4 h-4" /> Search
          </motion.button>
        </form>

        <datalist id="jp-authors">
          {suggestions.authors.map(a => <option key={a} value={a} />)}
        </datalist>
        <datalist id="jp-books">
          {(suggestions.books || []).map(b => <option key={b} value={b} />)}
        </datalist>
        <div className="grid grid-cols-3 gap-2">
          <select value={filterStatus} onChange={e => setFilterStatus(e.target.value)} className={INPUT_CLASS}>
            <option value="">All statuses</option>
            <option value="unreviewed">Unreviewed</option>
            <option value="reviewed">Reviewed</option>
          </select>
          <input type="text" list="jp-authors" value={filterAuthor} onChange={e => setFilterAuthor(e.target.value)} placeholder="Author..." className={INPUT_CLASS} />
          <input type="text" list="jp-books" value={filterBook} onChange={e => setFilterBook(e.target.value)} placeholder="Book..." className={INPUT_CLASS} />
        </div>

        <div className="flex items-center justify-between">
          <span className="text-xs text-gray-500">{total} job{total !== 1 ? 's' : ''} found</span>
          <button onClick={() => fetchJobs(page)} className="flex items-center gap-1 text-xs text-gray-400 hover:text-gray-200 transition-colors">
            <RefreshCw className="w-3 h-3" /> Refresh
          </button>
        </div>
      </div>

      {loading && <div className="flex justify-center py-8"><Loader2 className="w-6 h-6 animate-spin text-purple-400" /></div>}

      {error && (
        <div className="glass p-4 rounded-xl border-red-500/30 bg-red-500/10">
          <p className="text-sm text-red-400">{error}</p>
        </div>
      )}

      {!loading && !error && jobs.length === 0 && (
        <div className="glass p-8 rounded-2xl text-center">
          <FileText className="w-10 h-10 mx-auto mb-3 text-gray-600" />
          <p className="text-gray-400">No jobs found</p>
          <p className="text-xs text-gray-500 mt-1">Commit your first OCR job from the New Job tab</p>
        </div>
      )}

      {/* Results grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
        <AnimatePresence>
          {jobs.map(job => (
            <motion.button
              key={job.id}
              onClick={() => setSelectedJobId(job.id)}
              className="text-left glass p-4 rounded-xl border border-white/5 hover:border-white/20 hover:bg-white/5 transition-all"
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0 }}
              whileHover={{ scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
              layout
            >
              <div className="flex items-center flex-wrap gap-2 mb-2">
                <StatusBadge status={job.status} />
                <SyncBadge job={job} />
              </div>
              {job.book && <p className="text-sm font-medium text-gray-200 truncate">{job.book}</p>}
              <div className="flex items-center gap-2 mt-0.5">
                {job.chapter && <span className="text-xs text-gray-500">Ch. {job.chapter}</span>}
                {job.page && <span className="text-xs text-gray-500">p. {job.page}</span>}
              </div>
              {job.author && <p className="text-xs text-gray-400 mt-1">{job.author}</p>}
              <div className="flex items-center justify-between mt-2">
                <p className="text-xs text-gray-600 font-mono">{new Date(job.submitted_at).toLocaleDateString()}</p>
                {job.ocr_model && <span className="text-[10px] text-gray-500 truncate ml-2">{job.ocr_model}</span>}
              </div>
            </motion.button>
          ))}
        </AnimatePresence>
      </div>

      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-3">
          <button onClick={() => fetchJobs(page - 1)} disabled={page === 0} className="glass glass-hover p-2 rounded-lg disabled:opacity-30">
            <ChevronLeft className="w-4 h-4" />
          </button>
          <span className="text-sm text-gray-400">Page {page + 1} of {totalPages}</span>
          <button onClick={() => fetchJobs(page + 1)} disabled={page >= totalPages - 1} className="glass glass-hover p-2 rounded-lg disabled:opacity-30">
            <ChevronRight className="w-4 h-4" />
          </button>
        </div>
      )}
    </motion.div>
  )
}
