import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Printer, AlertCircle, Hash, Euro, FileText, X, ChevronDown, Loader2 } from 'lucide-react'
import toast from 'react-hot-toast'
import client from '../../../api/client'
import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, StatusBadge } from '../shared/TablePrimitives'
import StatCard from '../shared/StatCard'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import ExportButton from '../shared/ExportButton'
import { fmtNum, fmtEUR, fmtDate, fmtTime, fmtDateTime, fmtDateStr } from '../shared/reportDesignTokens'

function today() { return new Date().toISOString().slice(0, 10) }
function monthAgo() { const d = new Date(); d.setDate(d.getDate() - 30); return d.toISOString().slice(0, 10) }

// ─── Print Summary Modal ────────────────────────────────────────────────────

const PRINT_TYPES = [
  {
    id: 'quick',
    label: 'Γρήγορη Σύνοψη',
    desc: 'Συγκεντρωτικά στατιστικά — λίγο χαρτί',
  },
  {
    id: 'orders',
    label: 'Όλες οι Παραγγελίες',
    desc: 'Κάθε παραγγελία με σύνολο, χωρίς ανάλυση ειδών',
  },
  {
    id: 'detailed',
    label: 'Πλήρης Ανάλυση',
    desc: 'Κάθε παραγγελία + όλα τα είδη — καταναλώνει πολύ χαρτί',
  },
]

function PrintSummaryModal({ onClose, logs, stats, printers, printerF, queryParams }) {
  const [printType, setPrintType] = useState('quick')
  const [targetPrinter, setTargetPrinter] = useState('browser')
  const [itemBreakdown, setItemBreakdown] = useState(false)
  const [printing, setPrinting] = useState(false)

  const printerOptions = [
    { value: 'browser', label: 'Εκτύπωση μέσω browser' },
    ...printers.map(p => ({ value: String(p.id), label: p.name })),
  ]

  async function handlePrint() {
    if (targetPrinter !== 'browser') {
      await handleThermalPrint()
      return
    }
    handleBrowserPrint()
  }

  async function handleThermalPrint() {
    const printerTargetId = printerF === 'all' ? 0 : parseInt(printerF, 10)

    const body = {
      printer_target_id: printerTargetId,
      printer_id: parseInt(targetPrinter, 10),
      mode: printType,
      item_breakdown: itemBreakdown,
    }

    if (queryParams.business_day_id) {
      body.business_day_id = parseInt(queryParams.business_day_id, 10)
    } else {
      body.from_dt = queryParams.from || (new Date(Date.now() - 30 * 86400000).toISOString().slice(0, 10) + 'T00:00:00')
      body.to_dt = queryParams.to || (new Date().toISOString().slice(0, 10) + 'T23:59:59')
    }

    setPrinting(true)
    try {
      await client.post('/api/reports/print/printer', body)
      toast.success('Η εκτύπωση στάλθηκε στον εκτυπωτή')
      onClose()
    } catch {
      toast.error('Αποτυχία αποστολής στον εκτυπωτή')
    } finally {
      setPrinting(false)
    }
  }

  function handleBrowserPrint() {
    const win = window.open('', '_blank', 'width=820,height=750')
    if (!win) { onClose(); return }

    // ── Group logs by printer ──────────────────────────────────────────────
    // For "all printers" we produce one section per printer.
    // For a single selected printer the single section is the same format.
    const printerMap = {}
    for (const j of logs) {
      const key = j.printer_name
      if (!printerMap[key]) {
        printerMap[key] = { name: key, printJobs: 0, orderIds: new Set(), totalItems: 0, totalValue: 0, orders: [] }
      }
      const g = printerMap[key]
      g.printJobs += 1
      g.orderIds.add(j.order_id)
      const itemQty = (j.items || []).reduce((s, i) => s + i.quantity, 0)
      g.totalItems += itemQty
      if (j.order_total != null) g.totalValue += j.order_total
      g.orders.push(j)
    }

    // De-dup order totals per printer group (same order_id → count once)
    for (const g of Object.values(printerMap)) {
      const seen = {}
      g.totalValue = 0
      for (const j of g.orders) {
        if (j.success && j.order_total != null && !seen[j.order_id]) {
          seen[j.order_id] = true
          g.totalValue += j.order_total
        }
      }
    }

    const groups = Object.values(printerMap)
    const filterLabel = printerF === 'all'
      ? 'Όλοι οι Εκτυπωτές'
      : (printers.find(p => String(p.id) === printerF)?.name || printerF)

    // ── Period label ───────────────────────────────────────────────────────
    let periodRow = ''
    if (queryParams.business_day_id) {
      periodRow = `<div class="row"><span>Εργάσιμη Μέρα</span><span>${stats.periodLabel}</span></div>`
    } else {
      const fromStr = queryParams.from ? fmtDateStr(queryParams.from.slice(0, 10)) : '—'
      const toStr = queryParams.to ? fmtDateStr(queryParams.to.slice(0, 10)) : '—'
      periodRow = `<div class="row"><span>Από</span><span>${fromStr}</span></div>
                   <div class="row"><span>Έως</span><span>${toStr}</span></div>`
    }

    // ── Titles per mode ────────────────────────────────────────────────────
    const titles = {
      quick: 'Γρήγορη Ανάλυση Εκτυπώσεων',
      orders: 'Ανάλυση Εκτυπώσεων με Παραγγελίες',
      detailed: 'Αναλυτικό Ιστορικό Εκτυπώσεων',
    }

    // ── Render one printer block ───────────────────────────────────────────
    function renderPrinterBlock(g) {
      const orderCount = g.orderIds.size
      const statsBlock = `
        <div class="printer-header">
          <span>Εκτυπωτής</span><span>${g.name}</span>
        </div>
        <div class="divider"></div>
        <div class="row"><span>Εκτυπώσεις</span><span>${fmtNum(g.printJobs)}</span></div>
        <div class="row"><span>Παραγγελίες</span><span>${fmtNum(orderCount)}</span></div>
        <div class="row"><span>Είδη</span><span>${fmtNum(g.totalItems)}</span></div>
        <div class="row value-row"><span>Αξία Ειδών</span><span>${fmtEUR(g.totalValue)}</span></div>
      `

      if (printType === 'quick') {
        return `<div class="printer-block">${statsBlock}</div>`
      }

      if (printType === 'orders') {
        // Unique orders only
        const seenOrders = {}
        const orderLines = g.orders
          .filter(j => j.success)
          .filter(j => { if (seenOrders[j.order_id]) return false; seenOrders[j.order_id] = true; return true })
          .map(j => {
            const itemQty = (j.items || []).reduce((s, i) => s + i.quantity, 0)
            return `<div class="order-line">
              <span class="order-id">#${j.order_id} · ${j.table || '—'}</span>
              <span class="order-meta">${itemQty} είδη</span>
              <span class="order-value">${j.order_total != null ? fmtEUR(j.order_total) : '—'}</span>
            </div>`
          }).join('')
        return `<div class="printer-block">${statsBlock}<div class="divider"></div>${orderLines}</div>`
      }

      // detailed — full log, each entry is a print job
      const jobBlocks = g.orders.map(j => {
        const result = j.success ? '✓ Επιτυχία' : '✗ Αποτυχία'
        const itemRows = (j.items || []).map(i =>
          `<div class="item-row"><span>${i.name}</span><span>×${i.quantity}</span></div>`
        ).join('')
        return `
          <div class="job-block ${!j.success ? 'failed' : ''}">
            <div class="job-header">
              <span>#${j.order_id} · ${j.table || '—'}</span>
              <span>${fmtDateTime(j.printed_at)} · ${result}</span>
            </div>
            ${itemRows}
            ${j.order_total != null ? `<div class="job-total"><span>Σύνολο Παραγγελίας</span><span>${fmtEUR(j.order_total)}</span></div>` : ''}
          </div>`
      }).join('')

      return `<div class="printer-block">${statsBlock}<div class="divider"></div>${jobBlocks}</div>`
    }

    // ── Summary footer (multi-printer only) ───────────────────────────────
    function renderSummary() {
      if (groups.length <= 1) return ''
      const totJobs = groups.reduce((s, g) => s + g.printJobs, 0)
      const totOrders = groups.reduce((s, g) => s + g.orderIds.size, 0)
      const totItems = groups.reduce((s, g) => s + g.totalItems, 0)
      const totValue = groups.reduce((s, g) => s + g.totalValue, 0)
      return `
        <div class="summary-block">
          <div class="summary-title">Σύνολο Όλων των Εκτυπωτών</div>
          <div class="row"><span>Εκτυπώσεις</span><span>${fmtNum(totJobs)}</span></div>
          <div class="row"><span>Παραγγελίες</span><span>${fmtNum(totOrders)}</span></div>
          <div class="row"><span>Είδη</span><span>${fmtNum(totItems)}</span></div>
          <div class="row value-row"><span>Αξία Ειδών</span><span>${fmtEUR(totValue)}</span></div>
        </div>`
    }

    // ── Product breakdown (optional) ───────────────────────────────────────
    function renderItemBreakdown() {
      if (!itemBreakdown) return ''
      // Merge item counts across all printer groups
      const combined = {}
      for (const g of groups) {
        for (const j of g.orders) {
          if (!j.success) continue
          for (const i of (j.items || [])) {
            if (!combined[i.name]) combined[i.name] = { qty: 0 }
            combined[i.name].qty += i.quantity
          }
        }
      }
      if (!Object.keys(combined).length) return ''
      const sorted = Object.entries(combined).sort((a, b) => b[1].qty - a[1].qty)
      return `
        <div class="breakdown-block">
          <div class="breakdown-title">Ανάλυση Προϊόντων</div>
          ${sorted.map(([name, d]) => `
            <div class="breakdown-row">
              <span class="breakdown-name">${name}</span>
              <span class="breakdown-qty">${d.qty}</span>
            </div>`).join('')}
        </div>`
    }

    const styles = `
      <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: 'Courier New', monospace; font-size: 12px; color: #000; padding: 24px; max-width: 760px; }
        h1 { font-size: 16px; font-weight: bold; border-bottom: 2px solid #000; padding-bottom: 6px; margin-bottom: 12px; }
        .meta { margin-bottom: 16px; }
        .row { display: flex; justify-content: space-between; padding: 3px 0; }
        .divider { border-top: 1px dashed #999; margin: 6px 0; }
        .printer-block { border: 1px solid #ccc; border-radius: 4px; padding: 10px; margin-bottom: 14px; }
        .printer-header { display: flex; justify-content: space-between; font-weight: bold; font-size: 13px; margin-bottom: 4px; }
        .value-row { font-weight: bold; }
        .order-line { display: flex; gap: 8px; padding: 2px 0; font-size: 11px; }
        .order-id { flex: 1; }
        .order-meta { color: #666; min-width: 60px; text-align: right; }
        .order-value { min-width: 70px; text-align: right; font-weight: bold; }
        .job-block { margin-bottom: 8px; padding: 6px 0; border-bottom: 1px dotted #ddd; }
        .job-block:last-child { border-bottom: none; }
        .job-block.failed { color: #b00; }
        .job-header { display: flex; justify-content: space-between; font-weight: bold; font-size: 11px; margin-bottom: 3px; }
        .item-row { display: flex; justify-content: space-between; padding-left: 12px; font-size: 11px; color: #333; }
        .job-total { display: flex; justify-content: space-between; padding-left: 12px; font-size: 11px; font-weight: bold; margin-top: 3px; }
        .summary-block { border: 2px solid #000; border-radius: 4px; padding: 10px; margin-top: 8px; }
        .summary-title { font-weight: bold; font-size: 13px; margin-bottom: 6px; text-align: center; letter-spacing: 0.04em; }
        .breakdown-block { border: 1px solid #888; border-radius: 4px; padding: 10px; margin-top: 14px; }
        .breakdown-title { font-weight: bold; font-size: 13px; margin-bottom: 8px; letter-spacing: 0.04em; }
        .breakdown-row { display: flex; justify-content: space-between; padding: 2px 0; border-bottom: 1px dotted #ccc; font-size: 12px; }
        .breakdown-row:last-child { border-bottom: none; }
        .breakdown-name { flex: 1; }
        .breakdown-qty { font-weight: bold; min-width: 40px; text-align: right; }
        @media print { body { padding: 0; } }
      </style>
    `

    const htmlBody = `
      <h1>${titles[printType] || 'Αναφορά Εκτυπωτή'}</h1>
      <div class="meta">
        <div class="row"><span>Εκτυπωτής</span><span>${filterLabel}</span></div>
        ${periodRow}
        <div class="row"><span>Σύνολο Εγγραφών</span><span>${logs.length}</span></div>
      </div>
      ${groups.map(renderPrinterBlock).join('')}
      ${renderSummary()}
      ${renderItemBreakdown()}
    `

    win.document.write(`<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Ιστορικό Εκτυπωτή</title>${styles}</head><body>${htmlBody}</body></html>`)
    win.document.close()
    win.focus()
    win.print()
    onClose()
  }  // end handleBrowserPrint

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
      onMouseDown={e => { if (e.target === e.currentTarget) onClose() }}
    >
      <div className="relative w-full max-w-md rounded-xl border border-slate-200 bg-white shadow-xl">
        <div className="flex items-center justify-between border-b border-slate-100 px-5 py-4">
          <h2 className="text-[15px] font-semibold text-slate-900">Εκτύπωση Σύνοψης</h2>
          <button onClick={onClose} className="rounded-md p-1 text-slate-400 transition hover:bg-slate-100 hover:text-slate-600">
            <X className="h-4 w-4" />
          </button>
        </div>

        <div className="px-5 py-4 space-y-4 text-[13px] text-slate-700">
          <div>
            <div className="mb-2 text-[11px] font-medium uppercase tracking-[0.08em] text-slate-500">Τύπος Εκτύπωσης</div>
            <div className="space-y-2">
              {PRINT_TYPES.map(pt => (
                <label key={pt.id} className={`flex cursor-pointer items-start gap-3 rounded-lg border p-3 transition ${printType === pt.id ? 'border-sky-400 bg-sky-50' : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'}`}>
                  <input
                    type="radio"
                    name="printType"
                    value={pt.id}
                    checked={printType === pt.id}
                    onChange={() => setPrintType(pt.id)}
                    className="mt-0.5 accent-sky-500"
                  />
                  <div>
                    <div className="font-medium text-slate-800">{pt.label}</div>
                    <div className="text-[12px] text-slate-500">{pt.desc}</div>
                  </div>
                </label>
              ))}
            </div>
          </div>

          <label className="flex cursor-pointer items-start gap-3 rounded-lg border border-slate-200 p-3 transition hover:border-slate-300 hover:bg-slate-50">
            <input
              type="checkbox"
              checked={itemBreakdown}
              onChange={e => setItemBreakdown(e.target.checked)}
              className="mt-0.5 accent-sky-500"
            />
            <div>
              <div className="font-medium text-slate-800">Ανάλυση Προϊόντων</div>
              <div className="text-[12px] text-slate-500">Προσθέτει σύνολο τεμαχίων ανά προϊόν στο τέλος</div>
            </div>
          </label>

          <div>
            <div className="mb-2 text-[11px] font-medium uppercase tracking-[0.08em] text-slate-500">Εκτυπωτής Προορισμού</div>
            <div className="relative">
              <select
                value={targetPrinter}
                onChange={e => setTargetPrinter(e.target.value)}
                className="w-full appearance-none rounded-md border border-slate-200 bg-white py-2 pl-3 pr-8 text-[13px] text-slate-700 shadow-[0_1px_0_rgba(15,23,42,0.04)] focus:border-sky-400 focus:outline-none focus:ring-2 focus:ring-sky-100"
              >
                {printerOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
              </select>
              <ChevronDown className="pointer-events-none absolute right-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" />
            </div>
          </div>

          <div className="flex items-center justify-end gap-2 border-t border-slate-100 pt-2">
            <button
              onClick={onClose}
              className="inline-flex items-center justify-center gap-2 rounded-md border border-slate-200 bg-white px-3.5 py-2 text-[13px] font-medium text-slate-700 shadow-[0_1px_0_rgba(15,23,42,0.04)] transition hover:bg-slate-50 hover:border-slate-300"
            >
              Ακύρωση
            </button>
            <button
              onClick={handlePrint}
              disabled={printing}
              className="inline-flex items-center justify-center gap-2 rounded-md bg-sky-500 px-3.5 py-2 text-[13px] font-medium text-white shadow-[0_1px_0_rgba(15,23,42,0.08)] transition hover:bg-sky-600 active:bg-sky-700 disabled:opacity-60 disabled:pointer-events-none"
            >
              {printing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <FileText className="h-3.5 w-3.5" />}
              {printing ? 'Αποστολή...' : 'Εκτύπωση'}
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

// ─── Main Component ─────────────────────────────────────────────────────────

export default function PrinterHistory() {
  const [mode, setMode] = useState('range')
  const [from, setFrom] = useState(monthAgo())
  const [to, setTo] = useState(today())
  const [businessDayId, setBusinessDayId] = useState('all')
  const [printerF, setPrinterF] = useState('all')
  const [showPrintModal, setShowPrintModal] = useState(false)

  const { data: printersData } = useQuery({ queryKey: ['meta-printers'], queryFn: () => client.get('/api/reports/meta/printers').then(r => r.data), staleTime: 5 * 60 * 1000 })
  const { data: bdData } = useQuery({ queryKey: ['business-days-list'], queryFn: () => client.get('/api/reports/business-days').then(r => r.data), staleTime: 60 * 1000 })

  const queryParams = {
    ...(mode === 'workday' && businessDayId !== 'all' ? { business_day_id: businessDayId } : {}),
    ...(mode === 'range' ? { from: from + 'T00:00:00', to: to + 'T23:59:59' } : {}),
    ...(printerF !== 'all' ? { printer_id: printerF } : {}),
  }

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ['printer-history', mode, from, to, businessDayId, printerF],
    queryFn: () => client.get('/api/reports/printers/history', { params: queryParams }).then(r => r.data),
    staleTime: 60 * 1000,
  })

  const printers = printersData?.printers || []
  const printerOptions = [{ value: 'all', label: 'Όλοι οι Εκτυπωτές' }, ...printers.map(p => ({ value: String(p.id), label: p.name }))]
  const bdOptions = [{ value: 'all', label: 'Όλες οι Εργάσιμες Μέρες' }, ...((bdData?.business_days || []).map(bd => ({ value: String(bd.id), label: `${fmtDate(bd.opened_at)} · ${fmtTime(bd.opened_at)}` })))]

  const logs = data?.logs || []
  const total = data?.total || 0
  const failed = data?.failed || 0
  // total_amount comes pre-computed from the backend (unique orders, no double-counting reprints)
  const totalAmount = data?.total_amount ?? null

  // Derived stats for StatCards + Print modal
  const itemCounts = {}
  const waiterCounts = {}
  let totalItemQty = 0

  logs.forEach(l => {
    if (l.waiter) waiterCounts[l.waiter] = (waiterCounts[l.waiter] || 0) + 1
    ;(l.items || []).forEach(i => {
      itemCounts[i.name] = (itemCounts[i.name] || 0) + i.quantity
      totalItemQty += i.quantity
    })
  })

  const topItem = Object.entries(itemCounts).sort((a, b) => b[1] - a[1])[0]
  const periodLabel = mode === 'workday'
    ? (bdOptions.find(o => o.value === businessDayId)?.label || 'Εργάσιμη Μέρα')
    : `${fmtDateStr(from)} → ${fmtDateStr(to)}`

  const stats = { total, failed, totalAmount, itemCounts, waiterCounts, totalItemQty, periodLabel, topItem }

  if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={10} columns={7} /></div>
  if (isError) return (
    <div className="flex flex-col flex-1 min-h-0">
      <FilterBar><span className="text-[12px] text-slate-500">Αδυναμία φόρτωσης δεδομένων</span></FilterBar>
      <div className="flex flex-1 items-center justify-center"><button onClick={() => refetch()} className="rounded-md border border-slate-200 px-4 py-2 text-sm hover:bg-slate-50">Επανάληψη</button></div>
    </div>
  )

  return (
    <div className="flex flex-col flex-1 min-h-0">
      <FilterBar right={
        <div className="flex items-center gap-2">
          <button
            onClick={() => setShowPrintModal(true)}
            className="inline-flex items-center gap-1.5 rounded-md border border-slate-200 bg-white px-2.5 py-1.5 text-[12px] font-medium text-slate-600 shadow-[0_1px_0_rgba(15,23,42,0.04)] transition hover:border-slate-300 hover:bg-slate-50 hover:text-slate-900"
          >
            <FileText className="h-3.5 w-3.5" />
            Εκτύπωση Σύνοψης
          </button>
          <ExportButton endpoint="/api/reports/printers/export" params={queryParams} filename={`printer-history-${from}-to-${to}.csv`} />
        </div>
      }>
        <WorkDayDateToggle mode={mode} onChange={setMode} />
        {mode === 'workday' ? (
          <FilterSelect value={businessDayId} onChange={setBusinessDayId} options={bdOptions} width="w-72" label="Μέρα" />
        ) : (
          <>
            <FilterDateInput value={from} onChange={setFrom} label="Από" />
            <FilterDateInput value={to} onChange={setTo} label="Έως" />
          </>
        )}
        <FilterSelect value={printerF} onChange={setPrinterF} options={printerOptions} label="Εκτυπωτής" />
      </FilterBar>

      <div className="flex-1 overflow-y-auto p-6">
        <div className="grid grid-cols-4 gap-4 mb-4">
          <StatCard label="Συνολικές Εκτυπώσεις" value={fmtNum(total)} icon={Printer} />
          <StatCard label="Αποτυχημένες" value={fmtNum(failed)} sub={failed > 0 ? 'ελέγξτε τον εκτυπωτή' : 'όλα καλά'} icon={AlertCircle} />
          <StatCard label="Παραγγελίες Εκτυπώθηκαν" value={fmtNum(total - failed)} sub="επιτυχείς εκτυπώσεις" icon={Hash} />
          <StatCard
            label="Συνολικό Ποσό Παραγγελιών"
            value={totalAmount != null ? fmtEUR(totalAmount) : '—'}
            sub={totalAmount == null ? 'μη διαθέσιμο' : undefined}
            icon={Euro}
            accent={totalAmount != null}
          />
        </div>

        <Panel title="Εργασίες Εκτύπωσης" padded={false}>
          {logs.length === 0 ? (
            <EmptyState title="Δεν βρέθηκαν εργασίες εκτύπωσης" description="Δοκιμάστε διαφορετικό εύρος ημερομηνιών ή εκτυπωτή." />
          ) : (
            <>
              <DataTable>
                <THead>
                  <TH>Ώρα Εκτύπωσης</TH><TH>Εκτυπωτής</TH><TH>Παραγγελία #</TH><TH>Τραπέζι</TH><TH>Είδη</TH><TH>Αποτέλεσμα</TH>
                </THead>
                <tbody>
                  {logs.slice(0, 100).map(j => (
                    <TR key={j.id} striped className={!j.success ? 'bg-rose-50/40' : ''}>
                      <TD mono>{fmtDateTime(j.printed_at)}</TD>
                      <TD>{j.printer_name}</TD>
                      <TD mono>#{j.order_id}</TD>
                      <TD>{j.table}</TD>
                      <TD className="text-[12px] text-slate-600">
                        {(j.items || []).slice(0, 3).map((i, idx) => (
                          <span key={idx}>{i.name} ×{i.quantity}{idx < Math.min((j.items || []).length, 3) - 1 ? ', ' : ''}</span>
                        ))}
                        {(j.items || []).length > 3 && <span className="text-slate-400"> +{(j.items || []).length - 3} ακόμα</span>}
                      </TD>
                      <TD><StatusBadge status={j.success ? 'success' : 'failed'} /></TD>
                    </TR>
                  ))}
                </tbody>
              </DataTable>
              {logs.length > 100 && (
                <div className="border-t border-slate-100 bg-slate-50/50 px-4 py-2 text-center text-[11px] text-slate-500">
                  Εμφάνιση πρώτων 100 από {logs.length} εργασίες.
                </div>
              )}
            </>
          )}
        </Panel>
      </div>

      {showPrintModal && (
        <PrintSummaryModal
          onClose={() => setShowPrintModal(false)}
          logs={logs}
          stats={stats}
          printers={printers}
          printerF={printerF}
          queryParams={queryParams}
        />
      )}
    </div>
  )
}
