import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import client from '../../../api/client'
import { FilterBar, FilterSelect, FilterDateInput } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, StatusBadge } from '../shared/TablePrimitives'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import ExportButton from '../shared/ExportButton'
import { fmtNum, fmtDate, fmtTime, 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) }

export default function PrinterHealthLog() {
  const [from, setFrom] = useState(monthAgo())
  const [to, setTo] = useState(today())
  const [printerF, setPrinterF] = useState('all')

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

  const queryParams = {
    from: from + 'T00:00:00',
    to: to + 'T23:59:59',
    ...(printerF !== 'all' ? { printer_id: printerF } : {}),
  }

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

  const printerOptions = [{ value: 'all', label: 'Όλοι οι Εκτυπωτές' }, ...((printersData?.printers || []).map(p => ({ value: String(p.id), label: p.name })))]

  const logs = data?.logs || []
  const succeeded = logs.filter(j => j.success).length
  const failed = logs.filter(j => !j.success).length
  const rate = logs.length ? (succeeded / logs.length * 100) : 100

  if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={10} columns={6} /></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={
        <ExportButton endpoint="/api/reports/printers/export" params={queryParams} filename={`printer-health-${from}-to-${to}.csv`} />
      }>
        <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="rounded-lg border border-slate-200 bg-white p-5 shadow-[0_1px_0_rgba(15,23,42,0.04)] mb-4">
          <div className="grid grid-cols-3 divide-x divide-slate-200">
            <div className="px-2">
              <div className="text-[11px] font-medium uppercase tracking-[0.1em] text-slate-500">Επιτυχημένες</div>
              <div className="mt-1 font-mono text-[28px] font-medium tabular-nums text-emerald-600">{fmtNum(succeeded)}</div>
            </div>
            <div className="px-6">
              <div className="text-[11px] font-medium uppercase tracking-[0.1em] text-slate-500">Αποτυχημένες</div>
              <div className="mt-1 font-mono text-[28px] font-medium tabular-nums text-rose-600">{fmtNum(failed)}</div>
            </div>
            <div className="px-6">
              <div className="text-[11px] font-medium uppercase tracking-[0.1em] text-slate-500">Επιτυχία %</div>
              <div className="mt-1 font-mono text-[28px] font-medium tabular-nums text-slate-900">{rate.toFixed(1)}%</div>
            </div>
          </div>
        </div>

        <Panel title="Αρχείο Εργασιών" subtitle="Αποτυχημένες σε κόκκινο φόντο" padded={false}>
          {logs.length === 0 ? (
            <EmptyState title="Δεν βρέθηκαν εργασίες εκτύπωσης" description="Δοκιμάστε διαφορετικό εύρος ημερομηνιών ή εκτυπωτή." />
          ) : (
            <>
              <DataTable>
                <THead>
                  <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><StatusBadge status={j.success ? 'success' : 'failed'} /></TD>
                      <TD className="font-mono text-[11px] text-rose-700">
                        {j.error_message || <span className="text-slate-300">—</span>}
                      </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>
    </div>
  )
}
