import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Tag } 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 { fmtEUR, fmtNum, fmtDate, fmtTime, fmtDateTime, 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) }

export default function DiscountsLog() {
  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' ? { applied_by: waiterF } : {}),
  }

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ['discounts', mode, from, to, businessDayId, waiterF],
    queryFn: () => client.get('/api/reports/discounts', { 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 discounts = data?.discounts || []
  const byWaiter = data?.by_waiter || []
  const totalValue = data?.total_discount_value ?? 0
  const orderCount = data?.order_count ?? 0

  if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={8} 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>
        <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 space-y-4">
        {/* Summary cards */}
        <div className="grid grid-cols-3 gap-4">
          <StatCard label="Σύνολο Εκπτώσεων" value={fmtEUR(totalValue)} icon={Tag} color="amber" />
          <StatCard label="Παραγγελίες με Έκπτωση" value={fmtNum(orderCount)} color="slate" />
          <StatCard label="Αριθμός Εκπτώσεων" value={fmtNum(discounts.length)} color="slate" />
        </div>

        {/* By waiter summary */}
        {byWaiter.length > 1 && (
          <Panel title="Ανά Σερβιτόρο" padded={false}>
            <DataTable>
              <THead>
                <TH>Σερβιτόρος</TH>
                <TH align="right">Αριθμός</TH>
                <TH align="right">Σύνολο</TH>
                <TH align="right">Μέσος / Έκπτωση</TH>
              </THead>
              <tbody>
                {byWaiter.map(w => (
                  <TR key={w.waiter_id} striped>
                    <TD><WaiterAvatar name={w.waiter_name} id={w.waiter_id} /></TD>
                    <TD mono align="right">{fmtNum(w.count)}</TD>
                    <TD mono align="right" className="font-semibold text-amber-700">{fmtEUR(w.total_value)}</TD>
                    <TD mono align="right">{fmtEUR(w.count > 0 ? w.total_value / w.count : 0)}</TD>
                  </TR>
                ))}
              </tbody>
            </DataTable>
          </Panel>
        )}

        {/* Full log */}
        <Panel
          title="Αρχείο Εκπτώσεων"
          subtitle={`${discounts.length} εγγραφές — μόνο ανάγνωση`}
          padded={false}
        >
          {discounts.length === 0 ? (
            <EmptyState
              icon={Tag}
              title="Δεν βρέθηκαν εκπτώσεις"
              description="Δεν υπάρχουν εκπτώσεις για την επιλεγμένη περίοδο."
            />
          ) : (
            <DataTable>
              <THead>
                <TH>Ημ/νία</TH>
                <TH>Παραγγελία</TH>
                <TH>Σερβιτόρος</TH>
                <TH align="right">Τύπος</TH>
                <TH align="right">Τιμή πριν</TH>
                <TH align="right">Ποσό Έκπτωσης</TH>
                <TH>Αιτία</TH>
              </THead>
              <tbody>
                {discounts.map(d => {
                  const typeLabel = d.discount_type === 'percent'
                    ? `${d.discount_value}%`
                    : fmtEUR(d.discount_value)
                  const isItemLevel = d.item_id != null
                  return (
                    <TR key={d.id} striped>
                      <TD mono className="text-slate-500">{fmtDateTime(d.applied_at)}</TD>
                      <TD>
                        <span className="font-medium text-slate-900">
                          #{d.order_id}
                          {d.table_name && <span className="text-slate-400 font-normal ml-1">· {d.table_name}</span>}
                        </span>
                        {isItemLevel && (
                          <span className="ml-2 text-[10px] font-semibold px-1.5 py-0.5 rounded bg-slate-100 text-slate-500">ΑΝΤΙΚ.</span>
                        )}
                      </TD>
                      <TD><WaiterAvatar name={d.applied_by_name} id={d.applied_by_id} /></TD>
                      <TD mono align="right">
                        <span className={`text-xs font-semibold px-1.5 py-0.5 rounded ${d.discount_type === 'percent' ? 'bg-blue-50 text-blue-700' : 'bg-amber-50 text-amber-700'}`}>
                          {typeLabel}
                        </span>
                      </TD>
                      <TD mono align="right" className="text-slate-500">
                        {d.order_total_before != null ? fmtEUR(d.order_total_before) : '—'}
                      </TD>
                      <TD mono align="right" className="font-semibold text-amber-700">
                        − {fmtEUR(d.discount_amount)}
                      </TD>
                      <TD className="text-slate-500 text-[12px]">
                        {d.reason || <span className="text-slate-300">—</span>}
                      </TD>
                    </TR>
                  )
                })}
              </tbody>
              {discounts.length > 1 && (
                <tfoot>
                  <TR>
                    <TD colSpan={5} className="font-semibold text-slate-700">Σύνολο</TD>
                    <TD mono align="right" className="font-bold text-amber-700">− {fmtEUR(totalValue)}</TD>
                    <TD />
                  </TR>
                </tfoot>
              )}
            </DataTable>
          )}
        </Panel>
      </div>
    </div>
  )
}
