import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'
import client from '../../../api/client'
import { FilterBar, FilterDateInput } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, ChartTooltip } from '../shared/TablePrimitives'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import { fmtEUR, fmtNum, fmtDate, 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) }

const GRAN_OPTIONS = [['daily', 'Ημερήσια'], ['weekly', 'Εβδομαδιαία'], ['monthly', 'Μηνιαία']]

export default function RevenueTrends() {
  const [from, setFrom] = useState(monthAgo())
  const [to, setTo] = useState(today())
  const [gran, setGran] = useState('daily')

  const queryParams = { from: from + 'T00:00:00', to: to + 'T23:59:59', granularity: gran }

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

  const trends = data?.trends || []
  const anyHasProfit = trends.some(d => (d.profit || 0) > 0)
  const chartData = trends.map(d => ({
    label: gran === 'monthly' ? d.date : fmtDate(d.date),
    revenue: d.revenue,
    profit: (d.profit || 0) > 0 ? d.profit : undefined,
    rolling7: d.rolling7,
  }))

  if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={8} columns={3} 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>
        <FilterDateInput value={from} onChange={setFrom} label="Από" />
        <FilterDateInput value={to} onChange={setTo} label="Έως" />
        <div className="inline-flex rounded-md border border-slate-200 bg-slate-50 p-0.5 text-[12px]">
          {GRAN_OPTIONS.map(([g, label]) => (
            <button key={g} onClick={() => setGran(g)} className={`rounded px-2.5 py-1 font-medium transition ${gran === g ? 'bg-white text-slate-900 shadow-sm ring-1 ring-slate-200' : 'text-slate-500'}`}>
              {label}
            </button>
          ))}
        </div>
      </FilterBar>

      <div className="flex-1 overflow-y-auto p-6">
        <Panel title="Τάση Εσόδων" subtitle={`${GRAN_OPTIONS.find(([g]) => g === gran)?.[1] || gran} · ${fmtDateStr(from)} → ${fmtDateStr(to)}`}>
          {trends.length === 0 ? (
            <EmptyState title="Δεν υπάρχουν δεδομένα εσόδων" description="Δεν υπάρχουν κλειστές παραγγελίες σε αυτή την περίοδο." />
          ) : (
            <div style={{ height: 320 }}>
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={chartData} margin={{ top: 8, right: 16, bottom: 4, left: 4 }}>
                  <CartesianGrid vertical={false} stroke="#f1f5f9" />
                  <XAxis dataKey="label" tick={{ fontSize: 10, fill: '#94a3b8' }} stroke="#cbd5e1" axisLine={false} tickLine={false} />
                  <YAxis tick={{ fontSize: 11, fill: '#94a3b8' }} stroke="#cbd5e1" axisLine={false} tickLine={false} tickFormatter={v => '€' + v} />
                  <Tooltip content={<ChartTooltip formatter={v => fmtEUR(v)} />} />
                  <Legend wrapperStyle={{ fontSize: 11 }} iconType="rect" />
                  <Line type="monotone" dataKey="revenue" name="Έσοδα" stroke="#60a5fa" strokeWidth={2.5} dot={{ r: 3, fill: '#60a5fa' }} />
                  {anyHasProfit && <Line type="monotone" dataKey="profit" name="Κέρδος" stroke="#34d399" strokeWidth={2} dot={{ r: 3, fill: '#34d399' }} connectNulls={false} />}
                  {gran === 'daily' && <Line type="monotone" dataKey="rolling7" name="Μέσος 7 ημ." stroke="#94a3b8" strokeWidth={1.5} strokeDasharray="4 4" dot={false} />}
                </LineChart>
              </ResponsiveContainer>
            </div>
          )}
        </Panel>

        <div className="mt-4">
          <Panel title="Αναλυτικά Στοιχεία" padded={false}>
            <DataTable>
              <THead>
                <TH>Περίοδος</TH>
                <TH align="right">Παραγγελίες</TH>
                <TH align="right">Έσοδα</TH>
                {anyHasProfit && <TH align="right">Κέρδος</TH>}
                {gran === 'daily' && <TH align="right">Μέσος 7 ημ.</TH>}
              </THead>
              <tbody>
                {trends.map(d => (
                  <TR key={d.date} striped>
                    <TD className="font-medium">{gran === 'monthly' ? d.date : fmtDate(d.date)}</TD>
                    <TD mono align="right">{fmtNum(d.orders)}</TD>
                    <TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(d.revenue)}</TD>
                    {anyHasProfit && (
                      <TD mono align="right">
                        {(d.profit || 0) > 0
                          ? <span className="text-green-700">
                              {fmtEUR(d.profit)}
                              {d.has_gap && <span className="ml-1 text-[10px] text-amber-500">⚠</span>}
                            </span>
                          : <span className="text-slate-300">—</span>
                        }
                      </TD>
                    )}
                    {gran === 'daily' && <TD mono align="right" className="text-slate-500">{fmtEUR(d.rolling7)}</TD>}
                  </TR>
                ))}
              </tbody>
            </DataTable>
          </Panel>
        </div>
      </div>
    </div>
  )
}
