import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell, Legend } from 'recharts'
import { 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, ChartTooltip } from '../shared/TablePrimitives'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import ExportButton from '../shared/ExportButton'
import { fmtEUR, fmtNum, fmtDate, fmtTime, fmtDateStr, CHART_PALETTE } 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) }

// ─── SVG bar chart rendered as inline HTML ────────────────────────────────────
// Used inside the browser print window (no Recharts available there).

function svgBarChart(items, valueKey, labelKey, colorFn, width = 680, barH = 18, gap = 6) {
  const top5 = [...items].slice(0, 5)
  const maxVal = Math.max(1, ...top5.map(d => d[valueKey]))
  const labelW = 160
  const numW = 70
  const barAreaW = width - labelW - numW - 16
  const h = top5.length * (barH + gap) + gap

  const bars = top5.map((d, i) => {
    const y = gap + i * (barH + gap)
    const bw = Math.round((d[valueKey] / maxVal) * barAreaW)
    const color = colorFn(i)
    return `
      <text x="${labelW - 6}" y="${y + barH * 0.72}" text-anchor="end" font-size="11" fill="#475569" font-family="Arial,sans-serif">${d[labelKey]}</text>
      <rect x="${labelW}" y="${y}" width="${bw}" height="${barH}" rx="3" fill="${color}" />
      <text x="${labelW + bw + 4}" y="${y + barH * 0.72}" font-size="10" fill="#64748b" font-family="Arial,sans-serif">${d[valueKey]}</text>`
  }).join('')

  return `<svg width="${width}" height="${h}" xmlns="http://www.w3.org/2000/svg">${bars}</svg>`
}

// ─── Print modal ─────────────────────────────────────────────────────────────

const PRINT_TYPES = [
  { id: 'smart', label: 'Έξυπνη Σύνοψη', desc: 'Μόνο προϊόντα με πωλήσεις — σε σειρά ποσότητας' },
  { id: 'full',  label: 'Πλήρης Ανάλυση', desc: 'Όλα τα προϊόντα, ακόμα και με 0 πωλήσεις, με αξία + γραφήματα' },
]

function ProductPrintModal({ onClose, products, allProducts, printers, queryParams, periodLabel }) {
  const [printType, setPrintType] = useState('smart')
  const [targetPrinter, setTargetPrinter] = useState('browser')
  const [printing, setPrinting] = useState(false)

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

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

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

    const soldMap = {}
    for (const p of products) soldMap[p.product_id] = p

    const totalQty = products.reduce((s, p) => s + p.qty_sold, 0)
    const totalRev = products.reduce((s, p) => s + p.revenue, 0)

    let tableSection = ''
    if (printType === 'smart') {
      const sorted = [...products].sort((a, b) => b.qty_sold - a.qty_sold)
      const rows = sorted.map(p => {
        const pctRev = totalRev ? (p.revenue / totalRev * 100).toFixed(1) : '0'
        const pctQty = totalQty ? (p.qty_sold / totalQty * 100).toFixed(1) : '0'
        return `<tr>
          <td>${p.product_name}</td>
          <td class="num">${fmtNum(p.qty_sold)}</td>
          <td class="num">${fmtEUR(p.revenue)}</td>
          <td class="num">${pctRev}%</td>
          <td class="num">${pctQty}%</td>
        </tr>`
      }).join('')
      tableSection = `<table>
        <thead><tr><th>Προϊόν</th><th class="num">Τεμ.</th><th class="num">Έσοδα</th><th class="num">% Έσ.</th><th class="num">% Τεμ.</th></tr></thead>
        <tbody>${rows}</tbody>
        <tfoot><tr><td>Σύνολο</td><td class="num">${fmtNum(totalQty)}</td><td class="num">${fmtEUR(totalRev)}</td><td class="num">100%</td><td class="num">100%</td></tr></tfoot>
      </table>`
    } else {
      // Full: merge all products, including 0-sold
      const merged = allProducts.map(ap => {
        const sold = soldMap[ap.id]
        return { name: ap.name, category: ap.category_name, qty: sold ? sold.qty_sold : 0, revenue: sold ? sold.revenue : 0 }
      }).sort((a, b) => b.qty - a.qty)

      // Top-5 bar charts (qty and revenue)
      const top5qty = merged.filter(p => p.qty > 0).slice(0, 5)
      const top5rev = merged.filter(p => p.revenue > 0).slice(0, 5).sort((a, b) => b.revenue - a.revenue)

      const chartQty = svgBarChart(top5qty, 'qty', 'name', i => CHART_PALETTE[i % CHART_PALETTE.length])
      const maxRev = Math.max(1, ...top5rev.map(d => d.revenue))
      const labelW = 160, barH = 18, gap = 6, barAreaW = 680 - labelW - 90 - 16
      const revBars = top5rev.map((d, i) => {
        const y = gap + i * (barH + gap)
        const bw = Math.round((d.revenue / maxRev) * barAreaW)
        return `
          <text x="${labelW - 6}" y="${y + barH * 0.72}" text-anchor="end" font-size="11" fill="#475569" font-family="Arial,sans-serif">${d.name}</text>
          <rect x="${labelW}" y="${y}" width="${bw}" height="${barH}" rx="3" fill="${CHART_PALETTE[i % CHART_PALETTE.length]}" />
          <text x="${labelW + bw + 4}" y="${y + barH * 0.72}" font-size="10" fill="#64748b" font-family="Arial,sans-serif">${fmtEUR(d.revenue)}</text>`
      }).join('')
      const revH = top5rev.length * (barH + gap) + gap
      const chartRevSvg = `<svg width="680" height="${revH}" xmlns="http://www.w3.org/2000/svg">${revBars}</svg>`

      const rows = merged.map(p => {
        const pctRev = totalRev && p.revenue ? (p.revenue / totalRev * 100).toFixed(1) : '—'
        const pctQty = totalQty && p.qty ? (p.qty / totalQty * 100).toFixed(1) : '—'
        return `<tr class="${p.qty === 0 ? 'zero' : ''}">
          <td>${p.name}</td>
          <td class="cat">${p.category}</td>
          <td class="num">${fmtNum(p.qty)}</td>
          <td class="num">${fmtEUR(p.revenue)}</td>
          <td class="num">${pctRev}%</td>
          <td class="num">${pctQty}%</td>
        </tr>`
      }).join('')

      tableSection = `
        <div class="chart-section">
          <div class="chart-title">Top 5 σε Τεμάχια</div>
          ${chartQty}
        </div>
        <div class="chart-section">
          <div class="chart-title">Top 5 σε Έσοδα</div>
          ${chartRevSvg}
        </div>
        <table>
          <thead><tr><th>Προϊόν</th><th>Κατηγορία</th><th class="num">Τεμ.</th><th class="num">Έσοδα</th><th class="num">% Έσ.</th><th class="num">% Τεμ.</th></tr></thead>
          <tbody>${rows}</tbody>
          <tfoot><tr><td colspan="2">Σύνολο</td><td class="num">${fmtNum(totalQty)}</td><td class="num">${fmtEUR(totalRev)}</td><td class="num">100%</td><td class="num">100%</td></tr></tfoot>
        </table>`
    }

    const title = printType === 'smart' ? 'Έξυπνη Σύνοψη Προϊόντων' : 'Πλήρης Ανάλυση Προϊόντων'
    const styles = `<style>
      * { box-sizing: border-box; margin: 0; padding: 0; }
      body { font-family: Arial, sans-serif; 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; font-family: 'Courier New', monospace; }
      .meta { margin-bottom: 16px; font-family: 'Courier New', monospace; }
      .row { display: flex; justify-content: space-between; padding: 2px 0; }
      .chart-section { margin: 16px 0; }
      .chart-title { font-size: 11px; font-weight: bold; text-transform: uppercase; letter-spacing: .06em; color: #64748b; margin-bottom: 8px; }
      table { width: 100%; border-collapse: collapse; font-size: 11px; margin-top: 16px; font-family: 'Courier New', monospace; }
      th { text-align: left; border-bottom: 1px solid #000; padding: 4px 6px; font-size: 10px; text-transform: uppercase; letter-spacing: .05em; }
      td { padding: 3px 6px; border-bottom: 1px dotted #ccc; }
      .num { text-align: right; font-weight: bold; }
      .cat { color: #555; font-size: 10px; }
      .zero { color: #aaa; }
      tfoot td { border-top: 2px solid #000; border-bottom: none; font-weight: bold; padding-top: 6px; }
      @media print { body { padding: 0; } }
    </style>`

    win.document.write(`<!DOCTYPE html><html><head><meta charset="UTF-8"><title>${title}</title>${styles}</head><body>
      <h1>${title}</h1>
      <div class="meta">
        ${periodRow()}
        <div class="row"><span>Προϊόντα με πωλήσεις</span><span>${products.length}</span></div>
        ${printType === 'full' ? `<div class="row"><span>Σύνολο ενεργών προϊόντων</span><span>${allProducts.length}</span></div>` : ''}
      </div>
      ${tableSection}
    </body></html>`)
    win.document.close()
    win.focus()
    win.print()
    onClose()
  }

  async function handleThermalPrint() {
    const body = { printer_id: parseInt(targetPrinter, 10), mode: printType }
    if (queryParams.business_day_id) {
      body.business_day_id = parseInt(queryParams.business_day_id, 10)
    } else {
      body.from_dt = queryParams.from
      body.to_dt = queryParams.to
    }
    setPrinting(true)
    try {
      await client.post('/api/reports/print/products', body)
      toast.success('Η εκτύπωση στάλθηκε στον εκτυπωτή')
      onClose()
    } catch {
      toast.error('Αποτυχία αποστολής στον εκτυπωτή')
    } finally {
      setPrinting(false)
    }
  }

  function handlePrint() {
    if (targetPrinter === 'browser') handleBrowserPrint()
    else handleThermalPrint()
  }

  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>
          <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>
            {targetPrinter !== 'browser' && printType === 'full' && (
              <p className="mt-1.5 text-[11px] text-amber-600">Η Πλήρης Ανάλυση σε θερμικό θα εκτυπώσει μόνο τη λίστα χωρίς γραφήματα.</p>
            )}
          </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 ProductPerformance() {
  const [mode, setMode] = useState('range')
  const [from, setFrom] = useState(monthAgo())
  const [to, setTo] = useState(today())
  const [businessDayId, setBusinessDayId] = useState('all')
  const [catF, setCatF] = useState('all')
  const [chartMode, setChartMode] = useState('revenue')
  const [showPrintModal, setShowPrintModal] = useState(false)
  // 'revenue' | 'units' | 'profit' | 'dual'


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

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

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

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

  const products = data?.products || []
  const totalRev = products.reduce((s, p) => s + p.revenue, 0)
  const totalProfit = products.reduce((s, p) => s + (p.trackable_profit || 0), 0)
  const anyHasCost = products.some(p => (p.total_cost || 0) > 0)

  const top10 = [...products]
    .sort((a, b) => {
      if (chartMode === 'units') return b.qty_sold - a.qty_sold
      if (chartMode === 'profit') return (b.trackable_profit || 0) - (a.trackable_profit || 0)
      // revenue and dual: sort by revenue
      return b.revenue - a.revenue
    })
    .slice(0, 10)
    .map((p, i) => ({
      name: p.product_name,
      revenue: p.revenue,
      profit: p.has_gap ? null : (p.trackable_profit || 0),
      units: p.qty_sold,
      color: CHART_PALETTE[i % CHART_PALETTE.length],
    }))

  const periodLabel = mode === 'workday'
    ? (bdOptions.find(o => o.value === businessDayId)?.label || 'Εργάσιμη Μέρα')
    : `${fmtDateStr(from)} → ${fmtDateStr(to)}`

  if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={10} columns={7} showChart /></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/products/export" params={queryParams} filename={`products-${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="Έως" />
          </>
        )}
      </FilterBar>

      <div className="flex-1 overflow-y-auto p-6">
        {(() => {
          const chartModes = [
            ['revenue', 'Έσοδα'],
            ['units', 'Τεμάχια'],
            ...(anyHasCost ? [['profit', 'Κέρδος'], ['dual', 'Έσοδα vs Κέρδος']] : []),
          ]
          const subtitleMap = { revenue: 'έσοδα', units: 'τεμάχια', profit: 'κέρδος', dual: 'έσοδα vs κέρδος' }
          const isDual = chartMode === 'dual'
          return (
            <Panel title="Top 10 Προϊόντα" subtitle={`Ταξινομημένα κατά ${subtitleMap[chartMode] || 'έσοδα'}`} right={
              <div className="inline-flex rounded-md border border-slate-200 bg-slate-50 p-0.5 text-[11px]">
                {chartModes.map(([m, label]) => (
                  <button key={m} onClick={() => setChartMode(m)} className={`rounded px-2 py-1 font-medium transition ${chartMode === m ? 'bg-white text-slate-900 shadow-sm ring-1 ring-slate-200' : 'text-slate-500'}`}>{label}</button>
                ))}
              </div>
            }>
              {top10.length === 0 ? (
                <EmptyState title="Δεν υπάρχουν δεδομένα προϊόντων" description="Δεν υπάρχουν πωλήσεις σε αυτή την περίοδο." />
              ) : (
                <div style={{ height: isDual ? 320 : 280 }}>
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={top10} layout="vertical" margin={{ top: 4, right: 24, bottom: isDual ? 16 : 4, left: 4 }}>
                      <CartesianGrid horizontal={false} stroke="#f1f5f9" />
                      <XAxis type="number" tick={{ fontSize: 10, fill: '#94a3b8' }} stroke="#cbd5e1" axisLine={false} tickLine={false}
                        tickFormatter={v => chartMode === 'units' ? String(v) : '€' + v} />
                      <YAxis type="category" dataKey="name" tick={{ fontSize: 11, fill: '#475569' }} stroke="#cbd5e1" axisLine={false} tickLine={false} width={140} />
                      <Tooltip content={<ChartTooltip formatter={(v, name) => {
                        if (chartMode === 'units') return v + ' τεμ.'
                        return fmtEUR(v)
                      }} />} cursor={{ fill: '#f1f5f9' }} />
                      {isDual && <Legend wrapperStyle={{ fontSize: 11 }} iconType="rect" />}
                      {isDual ? (
                        <>
                          <Bar dataKey="revenue" name="Έσοδα" fill="#60a5fa" radius={[0, 0, 0, 0]} barSize={10} />
                          <Bar dataKey="profit" name="Κέρδος" fill="#34d399" radius={[0, 3, 3, 0]} barSize={10} />
                        </>
                      ) : (
                        <Bar dataKey={chartMode === 'units' ? 'units' : chartMode === 'profit' ? 'profit' : 'revenue'}
                          radius={[0, 3, 3, 0]} barSize={16}>
                          {top10.map((d, i) => (
                            <Cell key={i} fill={chartMode === 'profit' ? '#34d399' : d.color} />
                          ))}
                        </Bar>
                      )}
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              )}
            </Panel>
          )
        })()}

        <div className="mt-4">
          {(() => {
            const totalUncostedRev = products.reduce((s, p) => s + (p.uncosted_revenue || 0), 0)
            const totalCost = products.reduce((s, p) => s + (p.total_cost || 0), 0)
            const hasGap = products.some(p => p.has_gap)
            const overallMargin = totalRev > 0 && !hasGap
              ? ((totalProfit / totalRev) * 100).toFixed(0) + '%'
              : null
            return (
              <Panel
                title="Όλα τα Προϊόντα"
                subtitle={`${products.length} προϊόντα με πωλήσεις`}
                padded={false}
              >
                {hasGap && (
                  <div className="mx-4 mt-3 mb-1 flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2.5 text-[12px] text-amber-800">
                    <span className="shrink-0 font-bold">⚠</span>
                    <span>
                      Μερικά προϊόντα δεν έχουν κόστος — το κέρδος που φαίνεται είναι μερικό.
                      Ορισμένα έσοδα <strong>{fmtEUR(totalUncostedRev)}</strong> δεν συμπεριλαμβάνονται στο κέρδος.{' '}
                      <a href="/management?tab=products" className="underline hover:text-amber-900">Ορισμός κόστους προϊόντων →</a>
                    </span>
                  </div>
                )}
                {products.length === 0 ? (
                  <EmptyState title="Δεν βρέθηκαν προϊόντα" description="Δεν υπάρχουν πωλήσεις σε αυτή την περίοδο." />
                ) : (
                  <DataTable>
                    <THead>
                      <TH>Προϊόν</TH>
                      <TH align="right">Τεμάχια</TH>
                      <TH align="right">Έσοδα</TH>
                      {anyHasCost && <TH align="right">Κόστος</TH>}
                      <TH align="right">Κέρδος</TH>
                      <TH align="right">Απόβλητα</TH>
                      <TH align="right">% Έσόδων</TH>
                      {anyHasCost && <TH align="right">% Κέρδους</TH>}
                      <TH align="right">Παραγγελίες</TH>
                    </THead>
                    <tbody>
                      {products.map(p => {
                        const pctRev = totalRev ? (p.revenue / totalRev * 100) : 0
                        const pctProfit = totalProfit > 0 && !p.has_gap
                          ? (p.trackable_profit / totalProfit * 100)
                          : null
                        const margin = p.revenue > 0 && !p.has_gap && (p.total_cost || 0) > 0
                          ? ((p.trackable_profit / p.revenue) * 100).toFixed(0) + '%'
                          : null
                        return (
                          <TR key={p.product_id} striped>
                            <TD className="font-medium text-slate-900">{p.product_name}</TD>
                            <TD mono align="right">{fmtNum(p.qty_sold)}</TD>
                            <TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(p.revenue)}</TD>
                            {anyHasCost && (
                              <TD mono align="right">
                                {(p.total_cost || 0) > 0
                                  ? <span className="text-slate-600">{fmtEUR(p.total_cost)}</span>
                                  : <span className="text-slate-300">—</span>
                                }
                              </TD>
                            )}
                            <TD mono align="right">
                              {p.has_gap ? (
                                <span className="text-amber-500 text-[11px]">⚠ χωρίς κόστος</span>
                              ) : (p.total_cost || 0) === 0 ? (
                                <span className="text-slate-300">—</span>
                              ) : (
                                <span className={p.trackable_profit >= 0 ? 'text-green-700' : 'text-red-600'}>
                                  {fmtEUR(p.trackable_profit)}
                                  {margin && <span className="ml-1 text-[10px] text-slate-400">({margin})</span>}
                                </span>
                              )}
                            </TD>
                            <TD mono align="right">
                              {p.waste_qty > 0 ? (
                                <span className="text-amber-600">
                                  {p.waste_qty}
                                  {p.waste_cost > 0 && <span className="text-[10px] text-amber-400 ml-1">({fmtEUR(p.waste_cost)})</span>}
                                </span>
                              ) : <span className="text-slate-300">—</span>}
                            </TD>
                            <TD mono align="right">{pctRev.toFixed(1)}%</TD>
                            {anyHasCost && (
                              <TD mono align="right">
                                {pctProfit != null
                                  ? <span className="text-green-700">{pctProfit.toFixed(1)}%</span>
                                  : <span className="text-slate-300">—</span>
                                }
                              </TD>
                            )}
                            <TD mono align="right">{fmtNum(p.order_count)}</TD>
                          </TR>
                        )
                      })}
                    </tbody>
                    {products.length > 1 && (
                      <tfoot>
                        <TR>
                          <TD className="font-semibold text-slate-700" colSpan={2}>Σύνολο</TD>
                          <TD mono align="right" className="font-bold">{fmtEUR(totalRev)}</TD>
                          {anyHasCost && (
                            <TD mono align="right" className="font-bold text-slate-600">{fmtEUR(totalCost)}</TD>
                          )}
                          <TD mono align="right" className="font-bold">
                            {hasGap ? (
                              <span className="text-amber-600">{fmtEUR(totalProfit)}{' '}<span className="text-[10px]">+χωρίς κόστος</span></span>
                            ) : totalProfit > 0 ? (
                              <span className="text-green-700">
                                {fmtEUR(totalProfit)}
                                {overallMargin && <span className="ml-1 text-[10px] text-slate-400">({overallMargin})</span>}
                              </span>
                            ) : <span className="text-slate-300">—</span>}
                          </TD>
                          <TD />
                          <TD mono align="right" className="font-bold">100%</TD>
                          {anyHasCost && (
                            <TD mono align="right" className="font-bold text-green-700">
                              {totalProfit > 0 && !hasGap ? '100%' : '—'}
                            </TD>
                          )}
                          <TD />
                        </TR>
                      </tfoot>
                    )}
                  </DataTable>
                )}
              </Panel>
            )
          })()}
        </div>
      </div>

      {showPrintModal && (
        <ProductPrintModal
          onClose={() => setShowPrintModal(false)}
          products={products}
          allProducts={allProducts}
          printers={printers}
          queryParams={queryParams}
          periodLabel={periodLabel}
        />
      )}
    </div>
  )
}
