import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
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 } from '../shared/TablePrimitives'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import ExportButton from '../shared/ExportButton'
import { fmtEUR, fmtNum, fmtMinutes, fmtDate, fmtTime, 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 modal ─────────────────────────────────────────────────────────────

const PRINT_TYPES = [
  { id: 'smart', label: 'Έξυπνη Σύνοψη', desc: 'Κατάταξη τραπεζιών με παραγγελίες, μέση διάρκεια και έσοδα' },
  { id: 'full',  label: 'Πλήρης Ανάλυση', desc: 'Ίδιο, με επιπλέον μέσο έσοδο ανά επίσκεψη' },
]

function TablePrintModal({ onClose, tables, 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 handleBrowserPrint() {
    const win = window.open('', '_blank', 'width=820,height=750')
    if (!win) { onClose(); return }

    let periodRow = ''
    if (queryParams.business_day_id) {
      periodRow = `<div class="row"><span>Εργάσιμη Μέρα</span><span>${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>`
    }

    const totalOrders = tables.reduce((s, t) => s + t.order_count, 0)
    const totalRev = tables.reduce((s, t) => s + t.revenue, 0)

    const rows = tables.map(t => {
      const avgRev = t.order_count ? t.revenue / t.order_count : 0
      const dur = t.avg_duration_minutes != null ? fmtMinutes(t.avg_duration_minutes) : '—'
      if (printType === 'smart') {
        return `<tr>
          <td>${t.table_name}</td>
          <td class="num">${fmtNum(t.order_count)}</td>
          <td class="num">${dur}</td>
          <td class="num">${fmtEUR(t.revenue)}</td>
        </tr>`
      }
      return `<tr>
        <td>${t.table_name}</td>
        <td class="num">${fmtNum(t.order_count)}</td>
        <td class="num">${dur}</td>
        <td class="num">${fmtEUR(avgRev)}</td>
        <td class="num">${fmtEUR(t.revenue)}</td>
      </tr>`
    }).join('')

    const headers = printType === 'smart'
      ? `<th>Τραπέζι</th><th class="num">Παραγγελίες</th><th class="num">Μ. Διάρκεια</th><th class="num">Έσοδα</th>`
      : `<th>Τραπέζι</th><th class="num">Παραγγελίες</th><th class="num">Μ. Διάρκεια</th><th class="num">Μ. / Επίσκεψη</th><th class="num">Έσοδα</th>`
    const footCols = printType === 'smart'
      ? `<td>Σύνολο</td><td class="num">${fmtNum(totalOrders)}</td><td class="num">—</td><td class="num">${fmtEUR(totalRev)}</td>`
      : `<td>Σύνολο</td><td class="num">${fmtNum(totalOrders)}</td><td class="num">—</td><td class="num">—</td><td class="num">${fmtEUR(totalRev)}</td>`

    const title = printType === 'smart' ? 'Σύνοψη Τραπεζιών' : 'Πλήρης Ανάλυση Τραπεζιών'
    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: 800px; }
      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: 2px 0; }
      table { width: 100%; border-collapse: collapse; font-size: 11px; margin-top: 8px; }
      th { text-align: left; border-bottom: 1px solid #000; padding: 4px 6px; font-size: 10px; text-transform: uppercase; }
      td { padding: 3px 6px; border-bottom: 1px dotted #ccc; }
      .num { text-align: right; font-weight: bold; }
      tfoot td { border-top: 2px solid #000; border-bottom: none; font-weight: bold; padding-top: 6px; }
      @media print { body { padding: 0; } }
    </style>`

    const html = `<!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>${tables.length}</span></div>
      </div>
      <table>
        <thead><tr>${headers}</tr></thead>
        <tbody>${rows}</tbody>
        <tfoot><tr>${footCols}</tr></tfoot>
      </table>
    </body></html>`

    win.document.write(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/tables', 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>
          </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 TableAnalytics() {
  const [mode, setMode] = useState('range')
  const [from, setFrom] = useState(monthAgo())
  const [to, setTo] = useState(today())
  const [businessDayId, setBusinessDayId] = useState('all')
  const [showPrintModal, setShowPrintModal] = useState(false)

  const { data: bdData } = useQuery({ queryKey: ['business-days-list'], queryFn: () => client.get('/api/reports/business-days').then(r => r.data), staleTime: 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' } : {}),
  }

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ['table-analytics', mode, from, to, businessDayId],
    queryFn: () => client.get('/api/reports/tables/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 printers = printersData?.printers || []
  const tables = data?.tables || []
  const maxRev = Math.max(1, ...tables.map(t => t.revenue))

  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} /></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/tables/performance" params={queryParams} filename={`tables-${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">
        {tables.length === 0 ? (
          <EmptyState title="Δεν υπάρχουν δεδομένα τραπεζιών" description="Δεν υπάρχουν κλειστές παραγγελίες σε αυτή την περίοδο." />
        ) : (
          <>
            <Panel title="Απόδοση Τραπεζιών" padded={false}>
              <DataTable>
                <THead>
                  <TH>Τραπέζι</TH><TH align="right">Παραγγελίες</TH><TH align="right">Μέση Διάρκεια</TH>
                  <TH align="right">Μέσο / Επίσκεψη</TH><TH align="right">Συνολικά Έσοδα</TH><TH align="right">Κύκλοι</TH>
                </THead>
                <tbody>
                  {tables.map(t => {
                    const avgRev = t.order_count ? t.revenue / t.order_count : 0
                    return (
                      <TR key={t.table_id} striped>
                        <TD className="font-medium text-slate-900">{t.table_name}</TD>
                        <TD mono align="right">{fmtNum(t.order_count)}</TD>
                        <TD mono align="right">{fmtMinutes(t.avg_duration_minutes)}</TD>
                        <TD mono align="right">{fmtEUR(avgRev)}</TD>
                        <TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(t.revenue)}</TD>
                        <TD mono align="right">{fmtNum(t.order_count)}</TD>
                      </TR>
                    )
                  })}
                </tbody>
              </DataTable>
            </Panel>

            <div className="mt-4">
              <Panel title="Ένταση Εσόδων" subtitle="Χρώμα κελιού = έσοδα ως προς κορυφαίο τραπέζι">
                <div className="grid grid-cols-6 gap-3 sm:grid-cols-8 md:grid-cols-10">
                  {tables.map(t => {
                    const intensity = t.revenue / maxRev
                    return (
                      <div
                        key={t.table_id}
                        className="aspect-square flex flex-col justify-between rounded-md p-2 ring-1 ring-inset ring-slate-200"
                        style={{ backgroundColor: `rgba(96, 165, 250, ${0.08 + intensity * 0.65})` }}
                      >
                        <div className="font-mono text-[11px] font-semibold text-slate-700">{t.table_name}</div>
                        <div className="font-mono text-[10px] tabular-nums text-slate-700">{fmtEUR(t.revenue)}</div>
                      </div>
                    )
                  })}
                </div>
              </Panel>
            </div>
          </>
        )}
      </div>

      {showPrintModal && (
        <TablePrintModal
          onClose={() => setShowPrintModal(false)}
          tables={tables}
          printers={printers}
          queryParams={queryParams}
          periodLabel={periodLabel}
        />
      )}
    </div>
  )
}
