import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import client from '../../../api/client'
import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, StatusBadge, WaiterAvatar, ChartTooltip } from '../shared/TablePrimitives'
import OrderDetailModal from '../shared/OrderDetailModal'
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) }

const STATUS_OPTIONS = [
  { value: 'all', label: 'Όλες οι Καταστάσεις' },
  { value: 'open', label: 'Ανοιχτή' },
  { value: 'paid', label: 'Πληρωμένη' },
  { value: 'closed', label: 'Κλειστή' },
  { value: 'cancelled', label: 'Ακυρωμένη' },
]

export default function OrderHistory({ initialBusinessDayId } = {}) {
  const [mode, setMode] = useState(initialBusinessDayId ? 'workday' : 'range')
  const [from, setFrom] = useState(monthAgo())
  const [to, setTo] = useState(today())
  const [businessDayId, setBusinessDayId] = useState(initialBusinessDayId ? String(initialBusinessDayId) : 'all')
  const [statusF, setStatusF] = useState('all')
  const [waiterF, setWaiterF] = useState('all')
  const [tableF, setTableF] = useState('all')
  const [drillOrder, setDrillOrder] = useState(null)

  const { data: waitersData } = useQuery({ queryKey: ['meta-waiters'], queryFn: () => client.get('/api/reports/meta/waiters').then(r => r.data), staleTime: 5 * 60 * 1000 })
  const { data: tablesData } = useQuery({ queryKey: ['meta-tables'], queryFn: () => client.get('/api/reports/meta/tables').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' } : {}),
    ...(statusF !== 'all' ? { status: statusF } : {}),
    ...(waiterF !== 'all' ? { waiter_id: waiterF } : {}),
    ...(tableF !== 'all' ? { table_id: tableF } : {}),
    page_size: 200,
  }

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ['order-history', mode, from, to, businessDayId, statusF, waiterF, tableF],
    queryFn: () => client.get('/api/reports/orders/history', { 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 tableOptions = [{ value: 'all', label: 'Όλα τα Τραπέζια' }, ...((tablesData?.tables || []).map(t => ({ value: String(t.id), label: t.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 orders = Array.isArray(data) ? data : []

  if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={10} 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/orders/export" params={queryParams} filename={`orders-${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={statusF} onChange={setStatusF} options={STATUS_OPTIONS} label="Κατάσταση" />
        <FilterSelect value={waiterF} onChange={setWaiterF} options={waiterOptions} label="Σερβιτόρος" />
        <FilterSelect value={tableF} onChange={setTableF} options={tableOptions} label="Τραπέζι" />
      </FilterBar>

      <div className="flex-1 overflow-y-auto p-6">
        <Panel
          padded={false}
          title={
            <span className="flex items-center gap-1.5">
              <span>Παραγγελίες</span>
              <span className="text-slate-300">·</span>
              <span className="font-normal text-slate-500">{orders.length} αποτελέσματα</span>
            </span>
          }
          right={
            <span className="text-[11px] text-slate-400 italic">Κάντε Click για Λεπτομέρειες Παραγγελίας</span>
          }
        >
          {orders.length === 0 ? (
            <EmptyState title="Δεν βρέθηκαν παραγγελίες" description="Δοκιμάστε διαφορετικό εύρος ημερομηνιών ή φίλτρο κατάστασης." />
          ) : (
            <>
              <DataTable>
                <THead>
                  <TH>#</TH><TH>Τραπέζι</TH><TH>Άνοιξε</TH><TH>Έκλεισε</TH>
                  <TH>Κατάσταση</TH><TH align="right">Είδη</TH><TH align="right">Ακυρώσεις</TH><TH align="right">Σύνολο</TH>
                </THead>
                <tbody>
                  {orders.slice(0, 200).map(o => {
                    const allItems = o.items || []
                    const activeItems = allItems.filter(i => i.status !== 'cancelled')
                    const cancelledItems = allItems.filter(i => i.status === 'cancelled')
                    const totalQty = allItems.reduce((s, i) => s + (i.quantity || 1), 0)
                    const cancelledQty = cancelledItems.reduce((s, i) => s + (i.quantity || 1), 0)
                    const total = activeItems.reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0)
                    const isCancelled = o.status === 'cancelled'
                    return (
                      <TR key={o.id} striped onClick={() => setDrillOrder(o)} className={isCancelled ? 'opacity-50' : ''}>
                        <TD mono>#{o.id}</TD>
                        <TD>{o.table_name ?? o.table_id}</TD>
                        <TD mono>{fmtDateTime(o.opened_at)}</TD>
                        <TD mono>{fmtDateTime(o.closed_at)}</TD>
                        <TD><StatusBadge status={o.status} /></TD>
                        <TD mono align="right">{totalQty}</TD>
                        <TD mono align="right">
                          {cancelledQty > 0
                            ? <span className="text-red-500 font-semibold">{cancelledQty}</span>
                            : <span className="text-slate-300">—</span>}
                        </TD>
                        <TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(total)}</TD>
                      </TR>
                    )
                  })}
                </tbody>
              </DataTable>
              {orders.length > 200 && (
                <div className="border-t border-slate-100 bg-slate-50/50 px-4 py-2 text-center text-[11px] text-slate-500">
                  Εμφάνιση πρώτων 200 από {orders.length} παραγγελίες. Περιορίστε τα φίλτρα για λιγότερα αποτελέσματα.
                </div>
              )}
            </>
          )}
        </Panel>
      </div>

      {drillOrder && (
        <OrderDetailModal order={drillOrder} onClose={() => setDrillOrder(null)} />
      )}
    </div>
  )
}
