import { useState, useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip,
  ResponsiveContainer, Legend, ComposedChart, Line,
} from 'recharts'
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 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) }

const METRICS = [
  { key: 'orders',        label: 'ΠΑΡΑΓΓΕΛΙΕΣ',  color: '#60a5fa' },
  { key: 'items',         label: 'ΕΙΔΗ',          color: '#34d399' },
  { key: 'cancellations', label: 'ΑΚΥΡΩΣΕΙΣ',     color: '#f87171' },
  { key: 'total',         label: 'ΕΣΟΔΑ',         color: '#a78bfa' },
  { key: 'hours_worked',  label: 'ΩΡΕΣ',          color: '#fb923c', rightAxis: true },
]

function fmtHours(h) {
  if (h == null) return '—'
  const hrs = Math.floor(h)
  const mins = Math.round((h - hrs) * 60)
  if (mins === 0) return `${hrs}ω`
  return `${hrs}ω ${mins}λ`
}

function CustomTooltip({ active, payload, label }) {
  if (!active || !payload?.length) return null
  return (
    <div style={{
      background: '#fff', border: '1px solid #e2e8f0', borderRadius: 8,
      padding: '10px 14px', fontSize: 12, boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
      minWidth: 160,
    }}>
      <div style={{ fontWeight: 700, color: '#1e293b', marginBottom: 6 }}>{label}</div>
      {payload.map(p => (
        <div key={p.dataKey} style={{ display: 'flex', justifyContent: 'space-between', gap: 16, color: '#475569', marginBottom: 2 }}>
          <span style={{ color: p.color, fontWeight: 600 }}>{p.name}</span>
          <span style={{ fontWeight: 600, color: '#1e293b' }}>
            {p.dataKey === 'total' ? fmtEUR(p.value)
              : p.dataKey === 'hours_worked' ? fmtHours(p.value)
              : fmtNum(p.value)}
          </span>
        </div>
      ))}
    </div>
  )
}

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 [activeMetrics, setActiveMetrics] = useState(new Set(['orders', 'items', 'cancellations', 'total']))
  const [stacked, setStacked] = useState(false)

  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 || `#${w.waiter_id}`,
    shortName: (w.waiter_name || '').split(' ')[0] || `#${w.waiter_id}`,
    orders: w.orders || 0,
    items: w.items || 0,
    cancellations: w.cancellations || 0,
    total: Math.round((w.total || 0) * 100) / 100,
    hours_worked: w.hours_worked || 0,
  })), [waiters])

  function toggleMetric(key) {
    setActiveMetrics(prev => {
      const next = new Set(prev)
      if (next.has(key)) { if (next.size > 1) next.delete(key) }
      else next.add(key)
      return next
    })
  }

  const showRightAxis = activeMetrics.has('hours_worked')
  const leftMetrics = METRICS.filter(m => !m.rightAxis && activeMetrics.has(m.key))
  const hasRevenue = activeMetrics.has('total')

  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="Επιλέξτε μετρικές και τύπο γραφήματος"
            right={
              <div className="flex items-center gap-1 rounded-md border border-slate-200 p-0.5 bg-slate-50">
                <button
                  onClick={() => setStacked(false)}
                  className={`rounded px-2.5 py-1 text-[11px] font-semibold transition-colors ${!stacked ? 'bg-white text-slate-800 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
                >
                  Ομαδοποίηση
                </button>
                <button
                  onClick={() => setStacked(true)}
                  className={`rounded px-2.5 py-1 text-[11px] font-semibold transition-colors ${stacked ? 'bg-white text-slate-800 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
                >
                  Στοίβαγμα
                </button>
              </div>
            }
          >
            {/* Metric checkboxes */}
            <div className="flex flex-wrap gap-2 mb-4">
              {METRICS.map(m => {
                const active = activeMetrics.has(m.key)
                return (
                  <button
                    key={m.key}
                    onClick={() => toggleMetric(m.key)}
                    className="flex items-center gap-1.5 rounded-full border px-3 py-1 text-[11px] font-bold uppercase tracking-wider transition-all"
                    style={{
                      borderColor: active ? m.color : '#e2e8f0',
                      background: active ? m.color + '18' : 'transparent',
                      color: active ? m.color : '#94a3b8',
                    }}
                  >
                    <span
                      style={{
                        width: 8, height: 8, borderRadius: '50%',
                        background: active ? m.color : '#cbd5e1', flexShrink: 0,
                      }}
                    />
                    {m.label}
                  </button>
                )
              })}
            </div>

            <div style={{ height: 260 }}>
              <ResponsiveContainer width="100%" height="100%">
                <ComposedChart data={chartData} layout="vertical" margin={{ top: 4, right: showRightAxis ? 60 : 24, bottom: 4, left: 8 }}>
                  <CartesianGrid horizontal={false} stroke="#f1f5f9" />
                  <XAxis
                    type="number"
                    tick={{ fontSize: 11, fill: '#94a3b8' }}
                    stroke="#cbd5e1" axisLine={false} tickLine={false}
                    tickFormatter={v => hasRevenue && leftMetrics.length === 1 ? `€${v}` : v}
                  />
                  {showRightAxis && (
                    <XAxis
                      xAxisId="right"
                      type="number"
                      orientation="top"
                      tick={{ fontSize: 11, fill: '#fb923c' }}
                      stroke="#fed7aa" axisLine={false} tickLine={false}
                      tickFormatter={v => `${v}ω`}
                    />
                  )}
                  <YAxis
                    type="category"
                    dataKey="name"
                    tick={{ fontSize: 12, fill: '#475569' }}
                    stroke="#cbd5e1" axisLine={false} tickLine={false}
                    width={90}
                    tickFormatter={v => v.length > 12 ? v.slice(0, 11) + '…' : v}
                  />
                  <Tooltip content={<CustomTooltip />} cursor={{ fill: '#f1f5f9' }} />
                  {METRICS.filter(m => !m.rightAxis && activeMetrics.has(m.key)).map(m => (
                    <Bar
                      key={m.key}
                      dataKey={m.key}
                      name={m.label}
                      fill={m.color}
                      radius={stacked ? 0 : [0, 3, 3, 0]}
                      barSize={stacked ? 20 : 10}
                      stackId={stacked ? 'stack' : undefined}
                    />
                  ))}
                  {activeMetrics.has('hours_worked') && (
                    <Bar
                      key="hours_worked"
                      xAxisId="right"
                      dataKey="hours_worked"
                      name="ΩΡΕΣ"
                      fill="#fb923c"
                      radius={[0, 3, 3, 0]}
                      barSize={6}
                      opacity={0.7}
                    />
                  )}
                </ComposedChart>
              </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>
                  <TH align="right">Ώρες</TH>
                  <TH align="right">Συνολική Αξία</TH>
                </THead>
                <tbody>
                  {[...waiters].sort((a, b) => (b.total || 0) - (a.total || 0)).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">
                        {w.cancellations > 0
                          ? <span className="text-red-500 font-semibold">{fmtNum(w.cancellations)}</span>
                          : <span className="text-slate-300">—</span>}
                      </TD>
                      <TD mono align="right">{fmtHours(w.hours_worked)}</TD>
                      <TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(w.total)}</TD>
                    </TR>
                  ))}
                </tbody>
              </DataTable>
            )}
          </Panel>
        </div>
      </div>
    </div>
  )
}
