import { useState, useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { ConciergeBell, Printer, Download, PrinterIcon, X, ChevronDown, ChevronUp } from 'lucide-react'
import toast from 'react-hot-toast'
import client from '../../api/client'
import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from './shared/FilterBar'
import StatCard from './shared/StatCard'
import SkeletonTable from './shared/SkeletonTable'
import { DataTable, THead, TH, TR, TD } from './shared/TablePrimitives'
import { fmtNum, fmtEUR, fmtDate, fmtDateTime } 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) }

// ── CSV export (client-side) ──────────────────────────────────────────────────

function downloadCSV(filename, rows, headers) {
  const escape = v => `"${String(v ?? '').replace(/"/g, '""')}"`
  const lines = [
    headers.map(escape).join(','),
    ...rows.map(r => r.map(escape).join(',')),
  ]
  const blob = new Blob([lines.join('\n')], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url; a.download = filename; a.click()
  URL.revokeObjectURL(url)
}

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

function PrintModal({ zone, queryParams, periodLabel, onClose }) {
  const [targetPrinter, setTargetPrinter] = useState('browser')
  const [printing, setPrinting] = useState(false)

  const { data: printersData } = useQuery({
    queryKey: ['printers-list'],
    queryFn: () => client.get('/api/reports/meta/printers').then(r => r.data),
    staleTime: 60_000,
  })
  const printers = printersData?.printers || []

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

  function handleBrowserPrint() {
    const items = [...zone.all_products].sort((a, b) => b.count - a.count)
    const totalItems = items.reduce((s, i) => s + i.count, 0)

    const rows = items.map(item => {
      const dots = '.'.repeat(Math.max(2, 42 - item.name.length - String(item.count).length))
      return `<tr><td>${item.name}</td><td style="text-align:right;font-family:monospace;white-space:nowrap">${dots} ${item.count}</td></tr>`
    }).join('')

    const html = `<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Ζώνη: ${zone.name}</title>
<style>* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: Arial,sans-serif; font-size: 12px; color: #000; padding: 24px; max-width: 680px; }
h1 { font-size: 15px; font-weight: bold; font-family: 'Courier New',monospace; border-bottom: 2px solid #000; padding-bottom: 6px; margin-bottom: 10px; }
.meta { font-size: 11px; color: #555; margin-bottom: 14px; }
table { width: 100%; border-collapse: collapse; font-size: 12px; }
td { padding: 4px 4px; border-bottom: 1px dotted #ccc; }
tfoot td { border-top: 2px solid #000; border-bottom: none; font-weight: bold; padding-top: 8px; }
@media print { body { padding: 0; } }</style></head>
<body>
<h1>ΖΩΝΗ ΠΡΟΕΤΟΙΜΑΣΙΑΣ: ${zone.name.toUpperCase()}</h1>
<div class="meta">Περίοδος: ${periodLabel}</div>
<table>
<thead><tr><th style="text-align:left">Προϊόν</th><th style="text-align:right">Ποσότητα</th></tr></thead>
<tbody>${rows}</tbody>
<tfoot><tr><td>ΣΥΝΟΛΟ ΕΙΔΩΝ</td><td style="text-align:right">${totalItems}</td></tr></tfoot>
</table>
</body></html>`

    const win = window.open('', '_blank', 'width=800,height=600')
    win.document.write(html)
    win.document.close()
    win.focus()
    win.print()
    onClose()
  }

  async function handleThermalPrint() {
    setPrinting(true)
    try {
      const body = {
        printer_id: parseInt(targetPrinter, 10),
        zone_id: zone.id,
        ...queryParams,
      }
      await client.post('/api/reports/print/prep-zone', body)
      toast.success(`Αποστολή στον εκτυπωτή…`)
      onClose()
    } catch {
      toast.error('Αποτυχία εκτύπωσης')
    } finally {
      setPrinting(false)
    }
  }

  const isBrowser = targetPrinter === 'browser'

  return (
    <div
      style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}
      onClick={e => { if (e.target === e.currentTarget) onClose() }}
    >
      <div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 460, boxShadow: '0 20px 60px rgba(0,0,0,0.2)' }}>
        <div style={{ padding: '18px 22px', borderBottom: '1px solid #edeff1', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 15, fontWeight: 700 }}>Εκτύπωση Σύνοψης</div>
            <div style={{ fontSize: 12, color: '#5a6169', marginTop: 2 }}>Ζώνη: {zone.name} · {periodLabel}</div>
          </div>
          <button onClick={onClose} style={{ width: 28, height: 28, borderRadius: 8, border: '1px solid #edeff1', background: 'white', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <X size={14} />
          </button>
        </div>

        <div style={{ padding: '18px 22px', display: 'flex', flexDirection: 'column', gap: 14 }}>
          {/* Preview of shopping list */}
          <div style={{ background: '#f8fafc', borderRadius: 10, border: '1px solid #e2e8f0', padding: '10px 14px', maxHeight: 180, overflowY: 'auto', fontFamily: 'monospace', fontSize: 12 }}>
            {zone.all_products.slice(0, 20).map(p => {
              const dots = '.'.repeat(Math.max(2, 34 - p.name.length - String(p.count).length))
              return <div key={p.name}>{p.name}{dots}{p.count}</div>
            })}
            {zone.all_products.length > 20 && (
              <div style={{ color: '#94a3b8', marginTop: 4 }}>…+{zone.all_products.length - 20} ακόμα</div>
            )}
          </div>

          {/* Printer target */}
          <div>
            <label style={{ display: 'block', fontSize: 11, fontWeight: 700, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6 }}>Προορισμός</label>
            <select
              value={targetPrinter}
              onChange={e => setTargetPrinter(e.target.value)}
              style={{ width: '100%', border: '1px solid #d1d5db', borderRadius: 8, padding: '8px 10px', fontSize: 13, background: 'white', color: '#374151' }}
            >
              {printerOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
            </select>
          </div>

          {/* Action button */}
          <button
            onClick={isBrowser ? handleBrowserPrint : handleThermalPrint}
            disabled={printing}
            style={{
              width: '100%', padding: '10px 0', borderRadius: 10, border: 'none', cursor: 'pointer',
              background: '#3758c9', color: 'white', fontWeight: 700, fontSize: 14,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              opacity: printing ? 0.6 : 1,
            }}
          >
            <PrinterIcon size={16} />
            {printing ? 'Εκτύπωση…' : isBrowser ? 'Άνοιγμα / Εκτύπωση PDF' : 'Αποστολή στον Εκτυπωτή'}
          </button>
        </div>
      </div>
    </div>
  )
}

// ── Zone multi-select filter ──────────────────────────────────────────────────

function ZoneFilter({ zones, selected, onChange }) {
  const allSelected = selected.length === 0 || selected.length === zones.length

  function toggleAll() { onChange([]) }
  function toggle(id) {
    if (allSelected) {
      onChange([id])
    } else {
      const next = selected.includes(id) ? selected.filter(z => z !== id) : [...selected, id]
      onChange(next.length === zones.length ? [] : next)
    }
  }

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
      <span style={{ fontSize: 11, fontWeight: 600, color: '#8a9099', textTransform: 'uppercase', letterSpacing: 0.5 }}>Ζώνες:</span>
      <button
        onClick={toggleAll}
        style={{
          padding: '3px 10px', borderRadius: 999, fontSize: 11, fontWeight: 700,
          border: `1.5px solid ${allSelected ? '#3758c9' : '#d1d5db'}`,
          background: allSelected ? '#3758c9' : 'white',
          color: allSelected ? 'white' : '#374151',
          cursor: 'pointer',
        }}
      >
        Όλες
      </button>
      {zones.map(z => {
        const on = !allSelected && selected.includes(z.id)
        return (
          <button
            key={z.id}
            onClick={() => toggle(z.id)}
            style={{
              padding: '3px 10px', borderRadius: 999, fontSize: 11, fontWeight: 700,
              border: `1.5px solid ${on ? '#3758c9' : '#d1d5db'}`,
              background: on ? '#3758c9' : 'white',
              color: on ? 'white' : '#374151',
              cursor: 'pointer',
            }}
          >
            {z.name}
          </button>
        )
      })}
    </div>
  )
}

// ── Zone detail card ──────────────────────────────────────────────────────────

function ZoneDetailCard({ zone, queryParams, periodLabel }) {
  const [showPrintModal, setShowPrintModal] = useState(false)
  const [ordersExpanded, setOrdersExpanded] = useState(false)

  function handleCSVItems() {
    downloadCSV(
      `prep-zone-${zone.name}-items.csv`,
      zone.all_products.map(p => [p.name, p.count, p.value]),
      ['Προϊόν', 'Ποσότητα', 'Αξία (€)'],
    )
  }

  function handleCSVOrders() {
    downloadCSV(
      `prep-zone-${zone.name}-orders.csv`,
      zone.all_orders.map(o => [o.order_id, o.table, o.opened_at ? new Date(o.opened_at).toLocaleString('el-GR') : '', o.items_count, o.value]),
      ['Αρ. Παραγγελίας', 'Τραπέζι', 'Ώρα', 'Τεμάχια', 'Αξία (€)'],
    )
  }

  return (
    <>
      <div style={{
        border: '1px solid #e2e8f0', borderRadius: 14, overflow: 'hidden',
        background: 'white', boxShadow: '0 1px 3px rgba(0,0,0,0.06)',
        marginBottom: 16,
      }}>
        {/* Zone header bar */}
        <div style={{
          padding: '16px 20px', background: '#fafbff', borderBottom: '1px solid #e2e8f0',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12,
        }}>
          <div>
            <div style={{ fontSize: 16, fontWeight: 700, color: '#111315', display: 'flex', alignItems: 'center', gap: 8 }}>
              <ConciergeBell size={16} style={{ color: '#3758c9' }} />
              {zone.name}
              {zone.notification_name && zone.notification_name !== zone.name && (
                <span style={{ fontSize: 12, color: '#8a9099', fontWeight: 500 }}>({zone.notification_name})</span>
              )}
            </div>
            {zone.printers.length > 0 && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 4 }}>
                <Printer size={11} style={{ color: '#8a9099' }} />
                <span style={{ fontSize: 11, color: '#8a9099' }}>{zone.printers.map(p => p.name).join(', ')}</span>
              </div>
            )}
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            {/* Stats */}
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 10, color: '#8a9099', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5 }}>Συνολικά Είδη</div>
              <div style={{ fontSize: 24, fontWeight: 700, color: '#111315', fontFamily: 'monospace' }}>{fmtNum(zone.item_count)}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 10, color: '#8a9099', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5 }}>Αξία</div>
              <div style={{ fontSize: 24, fontWeight: 700, color: '#3758c9', fontFamily: 'monospace' }}>{fmtEUR(zone.total_value)}</div>
            </div>

            {/* Actions */}
            <div style={{ display: 'flex', gap: 6 }}>
              <button
                onClick={() => setShowPrintModal(true)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 5,
                  padding: '6px 12px', borderRadius: 8, border: '1.5px solid #3758c9',
                  background: '#3758c9', color: 'white',
                  fontSize: 12, fontWeight: 700, cursor: 'pointer',
                }}
              >
                <PrinterIcon size={13} />
                Εκτύπωση
              </button>
            </div>
          </div>
        </div>

        {zone.item_count === 0 ? (
          <div style={{ padding: '32px 20px', textAlign: 'center', color: '#94a3b8', fontSize: 13 }}>
            Δεν βρέθηκαν παραγγελίες για αυτή την ζώνη στο επιλεγμένο διάστημα.
          </div>
        ) : (
          <div style={{ padding: '0 0 4px' }}>
            {/* Items table */}
            <div style={{ padding: '14px 20px 8px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: '#374151', textTransform: 'uppercase', letterSpacing: 0.5 }}>
                Είδη ({zone.all_products.length})
              </div>
              <button
                onClick={handleCSVItems}
                style={{
                  display: 'flex', alignItems: 'center', gap: 4,
                  padding: '4px 10px', borderRadius: 6, border: '1px solid #d1d5db',
                  background: 'white', color: '#374151', fontSize: 11, fontWeight: 600, cursor: 'pointer',
                }}
              >
                <Download size={11} />
                CSV Ειδών
              </button>
            </div>
            <DataTable>
              <THead>
                <TH>Προϊόν</TH>
                <TH>Ποσότητα</TH>
                <TH>Αξία</TH>
              </THead>
              <tbody>
                {zone.all_products.map((p, i) => (
                  <TR key={p.name} striped>
                    <TD className="font-medium">{p.name}</TD>
                    <TD mono>{fmtNum(p.count)}</TD>
                    <TD mono className="text-slate-500">{fmtEUR(p.value)}</TD>
                  </TR>
                ))}
              </tbody>
            </DataTable>

            {/* Orders section */}
            <div style={{ padding: '14px 20px 8px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <button
                onClick={() => setOrdersExpanded(v => !v)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 6,
                  background: 'none', border: 'none', cursor: 'pointer', padding: 0,
                  fontSize: 12, fontWeight: 700, color: '#374151', textTransform: 'uppercase', letterSpacing: 0.5,
                }}
              >
                {ordersExpanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
                Παραγγελίες ({zone.all_orders.length})
              </button>
              {ordersExpanded && (
                <button
                  onClick={handleCSVOrders}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 4,
                    padding: '4px 10px', borderRadius: 6, border: '1px solid #d1d5db',
                    background: 'white', color: '#374151', fontSize: 11, fontWeight: 600, cursor: 'pointer',
                  }}
                >
                  <Download size={11} />
                  CSV Παραγγελιών
                </button>
              )}
            </div>
            {ordersExpanded && (
              <DataTable>
                <THead>
                  <TH>#</TH>
                  <TH>Τραπέζι</TH>
                  <TH>Ώρα</TH>
                  <TH>Τεμάχια</TH>
                  <TH>Αξία</TH>
                </THead>
                <tbody>
                  {zone.all_orders.map(o => (
                    <TR key={o.order_id} striped>
                      <TD mono className="text-slate-400 text-[11px]">#{o.order_id}</TD>
                      <TD className="font-medium">{o.table}</TD>
                      <TD className="text-slate-500 text-[12px]">
                        {o.opened_at ? new Date(o.opened_at).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' }) : '—'}
                      </TD>
                      <TD mono>{fmtNum(o.items_count)}</TD>
                      <TD mono className="text-slate-500">{fmtEUR(o.value)}</TD>
                    </TR>
                  ))}
                </tbody>
              </DataTable>
            )}
            <div style={{ height: 8 }} />
          </div>
        )}
      </div>

      {showPrintModal && (
        <PrintModal
          zone={zone}
          queryParams={queryParams}
          periodLabel={periodLabel}
          onClose={() => setShowPrintModal(false)}
        />
      )}
    </>
  )
}

// ── Main page ─────────────────────────────────────────────────────────────────

export default function PrepZonesPage() {
  const [mode, setMode] = useState('range')
  const [from, setFrom] = useState(monthAgo())
  const [to, setTo] = useState(today())
  const [businessDayId, setBusinessDayId] = useState('all')
  const [selectedZoneIds, setSelectedZoneIds] = useState([])   // [] = all

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

  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: ['prep-zones-report', mode, from, to, businessDayId],
    queryFn: () => client.get('/api/reports/prep-zones', { params: queryParams }).then(r => r.data),
    staleTime: 60_000,
  })

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

  const allZones = data?.zones || []

  const visibleZones = useMemo(() => {
    if (selectedZoneIds.length === 0) return allZones
    return allZones.filter(z => selectedZoneIds.includes(z.id))
  }, [allZones, selectedZoneIds])

  const totalItems = visibleZones.reduce((s, z) => s + z.item_count, 0)
  const totalValue = visibleZones.reduce((s, z) => s + z.total_value, 0)
  const busyZone = visibleZones.reduce((best, z) => (!best || z.item_count > best.item_count ? z : best), null)

  const periodLabel = useMemo(() => {
    if (mode === 'workday' && businessDayId !== 'all') {
      const bd = (bdData?.business_days || []).find(b => String(b.id) === businessDayId)
      return bd ? fmtDate(bd.opened_at) : `Εργάσιμη #${businessDayId}`
    }
    return `${from} – ${to}`
  }, [mode, businessDayId, from, to, bdData])

  if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={6} columns={4} /></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>
        <WorkDayDateToggle mode={mode} onChange={setMode} />
        {mode === 'workday' ? (
          <FilterSelect value={businessDayId} onChange={setBusinessDayId} options={bdOptions} label="Μέρα" />
        ) : (
          <>
            <FilterDateInput value={from} onChange={setFrom} label="Από" />
            <FilterDateInput value={to} onChange={setTo} label="Έως" />
          </>
        )}
      </FilterBar>

      {/* Zone multi-select */}
      {allZones.length > 1 && (
        <div style={{ padding: '10px 20px', borderBottom: '1px solid #e2e8f0', background: 'white' }}>
          <ZoneFilter
            zones={allZones}
            selected={selectedZoneIds}
            onChange={setSelectedZoneIds}
          />
        </div>
      )}

      <div className="flex-1 overflow-y-auto p-6">
        {/* Summary stats */}
        <div className="grid grid-cols-3 gap-4 mb-6">
          <StatCard label="Συνολικά Είδη" value={fmtNum(totalItems)} icon={ConciergeBell} />
          <StatCard label="Συνολική Αξία" value={fmtEUR(totalValue)} icon={ConciergeBell} accent />
          <StatCard
            label="Πιο Απασχολημένη Ζώνη"
            value={busyZone?.name || '—'}
            sub={busyZone ? `${fmtNum(busyZone.item_count)} είδη` : undefined}
          />
        </div>

        {allZones.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 gap-3 text-slate-400">
            <ConciergeBell size={36} className="opacity-40" />
            <p className="text-[15px] font-semibold text-slate-500">Δεν βρέθηκαν ζώνες προετοιμασίας</p>
            <p className="text-[13px]">Δημιουργήστε ζώνες από το Management → Prep Zones.</p>
          </div>
        ) : (
          <div>
            {visibleZones.map(zone => (
              <ZoneDetailCard
                key={zone.id}
                zone={zone}
                queryParams={queryParams}
                periodLabel={periodLabel}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
