import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { XCircle, TrendingDown, Repeat, CheckCircle2 } from 'lucide-react'
import client from '../../../api/client'
import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, WaiterAvatar } from '../shared/TablePrimitives'
import StatCard from '../shared/StatCard'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import ExportButton from '../shared/ExportButton'
import { fmtEUR, 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 CancellationsLog() {
  const [mode, setMode] = useState('range')
  const [from, setFrom] = useState(monthAgo())
  const [to, setTo] = useState(today())
  const [businessDayId, setBusinessDayId] = useState('all')
  const [waiterF, setWaiterF] = useState('all')

  const { data: waitersData } = useQuery({ queryKey: ['meta-waiters'], queryFn: () => client.get('/api/reports/meta/waiters').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' } : {}),
    ...(waiterF !== 'all' ? { waiter_id: waiterF } : {}),
  }

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

  const waiterOptions = [{ value: 'all', label: 'Όλοι οι Σερβιτόροι' }, ...((waitersData?.waiters || []).map(w => ({ value: String(w.id), label: w.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 cancellations = data?.cancellations || []
  const totalValue = data?.total_value || 0

  const itemCounts = {}
  cancellations.forEach(c => { itemCounts[c.product_name] = (itemCounts[c.product_name] || 0) + c.quantity })
  const topItem = Object.entries(itemCounts).sort((a, b) => b[1] - a[1])[0]

  if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={8} columns={8} /></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/cancellations/export" params={queryParams} filename={`cancellations-${from}-to-${to}.csv`} />
      }>
        <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={waiterF} onChange={setWaiterF} options={waiterOptions} label="Σερβιτόρος" />
      </FilterBar>

      <div className="flex-1 overflow-y-auto p-6">
        <div className="grid grid-cols-3 gap-4 mb-4">
          <StatCard label="Συνολικές Ακυρώσεις" value={fmtNum(cancellations.length)} sub="ακυρωμένα είδη" icon={XCircle} />
          <StatCard label="Συνολική Αξία Ακυρώσεων" value={fmtEUR(totalValue)} sub="χαμένα έσοδα" icon={TrendingDown} accent />
          <StatCard label="Πιο Ακυρωμένο" value={topItem ? topItem[0] : '—'} sub={topItem ? `${topItem[1]} τεμ.` : ''} icon={Repeat} />
        </div>

        <Panel title="Ακυρώσεις" padded={false}>
          {cancellations.length === 0 ? (
            <EmptyState icon={CheckCircle2} title="Δεν υπάρχουν ακυρώσεις" description="Δεν ακυρώθηκε τίποτα σε αυτή την περίοδο." />
          ) : (
            <>
              <DataTable>
                <THead>
                  <TH>Ώρα</TH><TH>Παραγγελία #</TH><TH>Τραπέζι</TH><TH>Σερβιτόρος</TH>
                  <TH>Είδος</TH><TH align="right">Αξία</TH><TH>Ακυρώθηκε από</TH><TH>Λόγος</TH>
                </THead>
                <tbody>
                  {cancellations.map(c => (
                    <TR key={c.id} striped>
                      <TD mono>{fmtDateTime(c.cancelled_at)}</TD>
                      <TD mono>#{c.order_id}</TD>
                      <TD>{c.table}</TD>
                      <TD><WaiterAvatar name={c.waiter_name} id={c.waiter_id} /></TD>
                      <TD>{c.product_name} <span className="text-slate-400">×{c.quantity}</span></TD>
                      <TD mono align="right" className="font-semibold text-rose-700">{fmtEUR(c.value)}</TD>
                      <TD className="text-slate-600">{c.cancelled_by || <span className="text-slate-300">—</span>}</TD>
                      <TD className="text-slate-500">{c.cancel_reason || <span className="text-slate-300">—</span>}</TD>
                    </TR>
                  ))}
                  <tr className="bg-rose-50/40">
                    <TD colSpan={5} className="py-3 text-right text-[11px] font-semibold uppercase tracking-wider text-slate-500">Σύνολο Ακυρωθέντων</TD>
                    <TD mono align="right" className="py-3 text-base font-semibold text-rose-700">{fmtEUR(totalValue)}</TD>
                    <TD colSpan={2} />
                  </tr>
                </tbody>
              </DataTable>
            </>
          )}
        </Panel>
      </div>
    </div>
  )
}
