import { useState, useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'
import { Flame, CalendarDays, Moon, TrendingUp } from 'lucide-react'
import client from '../../../api/client'
import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar'
import { Panel, ChartTooltip } from '../shared/TablePrimitives'
import StatCard from '../shared/StatCard'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import { 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 DOWS = ['Δευ', 'Τρι', 'Τετ', 'Πεμ', 'Παρ', 'Σαβ', 'Κυρ']
const HOURS = Array.from({ length: 14 }, (_, i) => 10 + i)

export default function TrafficAnalytics() {
  const [mode, setMode] = useState('range')
  const [from, setFrom] = useState(monthAgo())
  const [to, setTo] = useState(today())
  const [businessDayId, setBusinessDayId] = useState('all')

  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' } : {}),
  }

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

  const bdOptions = [{ value: 'all', label: 'Όλες οι Εργάσιμες Μέρες' }, ...((bdData?.business_days || []).map(bd => ({ value: String(bd.id), label: `${fmtDate(bd.opened_at)} · ${fmtTime(bd.opened_at)}` })))]

  const byHour = useMemo(() => {
    const hourMap = {}
    ;(data?.by_hour || []).forEach(h => { hourMap[h.hour] = h })
    return HOURS.map(h => hourMap[h] || { hour: h, orders: 0, revenue: 0 })
  }, [data])

  const byWeekday = data?.by_weekday || []

  const chartData = byHour.map(h => ({
    hour: `${String(h.hour).padStart(2, '0')}:00`,
    orders: h.orders,
  }))

  const busiest = [...byHour].sort((a, b) => b.orders - a.orders)[0]
  const busiestDow = [...byWeekday].sort((a, b) => b.orders - a.orders)[0]
  const quietest = [...byHour].filter(h => h.orders > 0).sort((a, b) => a.orders - b.orders)[0]

  if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={4} columns={5} 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>
  )

  const maxByHour = Math.max(1, ...byHour.map(h => h.orders))
  const maxByDow = Math.max(1, ...byWeekday.map(d => d.orders))

  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="Έως" />
          </>
        )}
      </FilterBar>

      <div className="flex-1 overflow-y-auto p-6">
        <div className="grid grid-cols-4 gap-4">
          <StatCard label="Πιο Πολυάσχολη Ώρα" value={busiest ? `${String(busiest.hour).padStart(2, '0')}:00` : '—'} icon={Flame} />
          <StatCard label="Πιο Πολυάσχολη Μέρα" value={busiestDow?.label || '—'} icon={CalendarDays} />
          <StatCard label="Πιο Ήσυχη Ώρα" value={quietest ? `${String(quietest.hour).padStart(2, '0')}:00` : '—'} icon={Moon} />
          <StatCard label="Συνολικές Παραγγελίες" value={fmtNum(byHour.reduce((s, h) => s + h.orders, 0))} icon={TrendingUp} accent />
        </div>

        <div className="mt-4">
          <Panel title="Παραγγελίες ανά Ώρα" subtitle="Σε όλες τις μέρες της επιλεγμένης περιόδου">
            <div style={{ height: 240 }}>
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={chartData} margin={{ top: 8, right: 8, bottom: 4, left: 4 }}>
                  <CartesianGrid vertical={false} stroke="#f1f5f9" />
                  <XAxis dataKey="hour" tick={{ fontSize: 10, fill: '#94a3b8' }} stroke="#cbd5e1" axisLine={false} tickLine={false} />
                  <YAxis tick={{ fontSize: 11, fill: '#94a3b8' }} stroke="#cbd5e1" axisLine={false} tickLine={false} />
                  <Tooltip content={<ChartTooltip />} cursor={{ fill: '#f1f5f9' }} />
                  <Bar dataKey="orders" fill="#60a5fa" radius={[3, 3, 0, 0]} maxBarSize={36} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </Panel>
        </div>

        <div className="mt-4">
          <Panel title="Παραγγελίες ανά Ημέρα Εβδομάδας" subtitle="Σωρευτικά σε επιλεγμένη περίοδο">
            <div className="grid grid-cols-7 gap-3">
              {byWeekday.map((d) => {
                const intensity = d.orders / maxByDow
                return (
                  <div key={d.day} className="flex flex-col items-center gap-2">
                    <div className="font-mono text-[11px] font-semibold uppercase tracking-wider text-slate-500">{d.label}</div>
                    <div
                      className="flex h-24 w-full items-end justify-center rounded-md pb-2"
                      style={{ backgroundColor: `rgba(96, 165, 250, ${0.08 + intensity * 0.7})` }}
                    >
                      <span className="font-mono text-[13px] font-semibold tabular-nums" style={{ color: intensity > 0.4 ? 'white' : '#334155' }}>
                        {d.orders}
                      </span>
                    </div>
                  </div>
                )
              })}
            </div>
          </Panel>
        </div>
      </div>
    </div>
  )
}
