import { useState, useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'
import client from '../../../api/client'
import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, WaiterAvatar, ChartTooltip } from '../shared/TablePrimitives'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import { fmtEUR, fmtNum, fmtDate, fmtTime } 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 Activity() {
  const [waiterId, setWaiterId] = useState('all')
  const [mode, setMode] = useState('range')
  const [from, setFrom] = useState(monthAgo())
  const [to, setTo] = useState(today())
  const [businessDayId, setBusinessDayId] = 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 = {
    ...(waiterId !== 'all' ? { waiter_id: waiterId } : {}),
    ...(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: ['shifts-activity', waiterId, mode, from, to, businessDayId],
    queryFn: () => client.get('/api/reports/shift/orders', { 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 waiters = data?.waiters || []

  const chartData = useMemo(() => waiters.map(w => ({
    name: (w.waiter_name || '').split(' ')[0],
    orders: w.orders,
  })), [waiters])

  if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={5} columns={7} showChart /></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>
        <FilterSelect value={waiterId} onChange={setWaiterId} options={waiterOptions} label="Σερβιτόρος" />
        <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="Έως" />
          </>
        )}
      </FilterBar>

      <div className="flex-1 overflow-y-auto p-6">
        {waiters.length > 0 && (
          <Panel title="Παραγγελίες ανά Σερβιτόρο" subtitle="Συνολικές παραγγελίες στην επιλεγμένη περίοδο">
            <div style={{ height: 240 }}>
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={chartData} layout="vertical" margin={{ top: 4, right: 24, bottom: 4, left: 4 }}>
                  <CartesianGrid horizontal={false} stroke="#f1f5f9" />
                  <XAxis type="number" tick={{ fontSize: 11, fill: '#94a3b8' }} stroke="#cbd5e1" axisLine={false} tickLine={false} />
                  <YAxis type="category" dataKey="name" tick={{ fontSize: 12, fill: '#475569' }} stroke="#cbd5e1" axisLine={false} tickLine={false} width={80} />
                  <Tooltip content={<ChartTooltip />} cursor={{ fill: '#f1f5f9' }} />
                  <Bar dataKey="orders" fill="#60a5fa" radius={[0, 3, 3, 0]} barSize={18} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </Panel>
        )}

        <div className="mt-4">
          <Panel title="Δραστηριότητα ανά Σερβιτόρο" padded={false}>
            {waiters.length === 0 ? (
              <EmptyState title="Δεν βρέθηκε δραστηριότητα" description="Δεν υπάρχουν παραγγελίες στην επιλεγμένη περίοδο." />
            ) : (
              <DataTable>
                <THead>
                  <TH>Σερβιτόρος</TH>
                  <TH align="right">Παραγγελίες</TH>
                  <TH align="right">Είδη</TH>
                  <TH align="right">Συνολική Αξία</TH>
                </THead>
                <tbody>
                  {waiters.sort((a, b) => b.total - a.total).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.orders)}</TD>
                      <TD mono align="right">{fmtNum(w.items)}</TD>
                      <TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(w.total)}</TD>
                    </TR>
                  ))}
                </tbody>
              </DataTable>
            )}
          </Panel>
        </div>
      </div>
    </div>
  )
}
