import { useEffect, useState } from 'react';
import {
  Bar,
  BarChart,
  CartesianGrid,
  Line,
  LineChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';
import { useIsDesktop } from '../../lib/useIsDesktop';
import { useAdminToken } from './AdminLayout';
import PageviewsChart from './PageviewsChart';

interface DailyStats {
  games_per_day: Record<string, number>;
  players_per_day: Record<string, number>;
  completion_rate: number | null;
  avg_game_duration_minutes: number | null;
  total_players: number;
  unconfirmed_players: number;
  peak_hours: Record<string, number>;
  rounds_per_day: Record<string, number>;
  pageviews_per_day: Record<string, number>;
  visitors_per_day: Record<string, number>;
  pageviews_per_day_by_device: Record<string, Record<string, number>>;
  pageviews_per_day_by_browser: Record<string, Record<string, number>>;
  pageviews_per_day_by_os: Record<string, Record<string, number>>;
  top_referrers: Record<string, number>;
  top_paths: Record<string, number>;
  browsers: Record<string, number>;
  operating_systems: Record<string, number>;
  device_types: Record<string, number>;
  countries: Record<string, number>;
}

function toSeries(byDay: Record<string, number>) {
  return Object.entries(byDay)
    .map(([day, n]) => ({ day, n }))
    .sort((a, b) => a.day.localeCompare(b.day));
}

function SummaryCard({ label, value }: { label: string; value: string }) {
  return (
    <div className="bg-header border border-[#142018] rounded-xl px-4 py-3 flex-1 min-w-[140px]">
      <p className="text-xs text-green-dim uppercase tracking-wide">{label}</p>
      <p className="font-serif text-xl text-gold mt-1">{value}</p>
    </div>
  );
}

function TimeSeriesChart({ title, data, kind = 'line' }: { title: string; data: Record<string, number>; kind?: 'line' | 'bar' }) {
  const series = toSeries(data);
  return (
    <div className="bg-header border border-[#142018] rounded-xl p-4">
      <p className="text-sm text-gold mb-2">{title}</p>
      <ResponsiveContainer width="100%" height={200}>
        {kind === 'line' ? (
          <LineChart data={series}>
            <CartesianGrid stroke="#142018" />
            <XAxis dataKey="day" tick={{ fill: '#9c906c', fontSize: 10 }} />
            <YAxis tick={{ fill: '#9c906c', fontSize: 10 }} allowDecimals={false} />
            <Tooltip contentStyle={{ background: '#070c09', border: '1px solid #142018' }} />
            <Line type="monotone" dataKey="n" stroke="#c9a84c" strokeWidth={2} dot={false} />
          </LineChart>
        ) : (
          <BarChart data={series}>
            <CartesianGrid stroke="#142018" />
            <XAxis dataKey="day" tick={{ fill: '#9c906c', fontSize: 10 }} />
            <YAxis tick={{ fill: '#9c906c', fontSize: 10 }} allowDecimals={false} />
            <Tooltip contentStyle={{ background: '#070c09', border: '1px solid #142018' }} />
            <Bar dataKey="n" fill="#c9a84c" />
          </BarChart>
        )}
      </ResponsiveContainer>
    </div>
  );
}

function BreakdownTable({ title, data }: { title: string; data: Record<string, number> }) {
  const rows = Object.entries(data).sort((a, b) => b[1] - a[1]);
  return (
    <div className="bg-header border border-[#142018] rounded-xl p-4">
      <p className="text-sm text-gold mb-2">{title}</p>
      {rows.length === 0 ? (
        <p className="text-xs text-green-dim">Žiadne dáta.</p>
      ) : (
        <table className="w-full text-sm">
          <tbody>
            {rows.map(([key, n]) => (
              <tr key={key} className="border-b border-gold/[.06] last:border-0">
                <td className="py-1 text-green-score truncate">{key || '—'}</td>
                <td className="py-1 text-right text-gold-dim">{n}</td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  );
}

type Scope = 'all' | 'logged_in';

function ScopeToggle({ scope, onChange }: { scope: Scope; onChange: (s: Scope) => void }) {
  return (
    <div className="flex rounded-lg overflow-hidden border border-gold/20 self-start">
      {(['all', 'logged_in'] as Scope[]).map((s) => (
        <button
          key={s}
          onClick={() => onChange(s)}
          className={`px-3 py-1.5 text-xs font-serif tracking-wide transition-colors ${
            scope === s ? 'bg-gold text-table' : 'bg-header text-green-dim hover:text-gold'
          }`}
        >
          {s === 'all' ? 'Všetci' : 'Prihlásení'}
        </button>
      ))}
    </div>
  );
}

export default function AdminStats() {
  const token = useAdminToken();
  const desktop = useIsDesktop();
  const [data, setData] = useState<DailyStats | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [scope, setScope] = useState<Scope>('all');

  useEffect(() => {
    let cancelled = false;
    const qs = scope === 'logged_in' ? '?logged_in=1' : '';
    fetch(`/api/admin/stats${qs}`, { headers: { Authorization: `Bearer ${token}` } })
      .then((res) => {
        if (res.status === 403) throw new Error('Neplatný token.');
        if (!res.ok) throw new Error('Chyba pri načítaní štatistík.');
        return res.json();
      })
      .then((json) => {
        if (!cancelled) setData(json);
      })
      .catch((e) => {
        if (!cancelled) setError(e.message);
      });
    return () => {
      cancelled = true;
    };
  }, [token, scope]);

  if (error) return <p className="text-red-400 text-sm">{error}</p>;
  if (!data) return <p className="text-green-dim text-sm">Načítavam...</p>;

  return (
    <div className="flex flex-col gap-4">
      <div className={`flex gap-3 ${desktop ? '' : 'flex-wrap'}`}>
        <SummaryCard label="Hráči celkom" value={String(data.total_players)} />
        <SummaryCard label="Nedokončené registrácie" value={String(data.unconfirmed_players)} />
        <SummaryCard
          label="Dokončené hry"
          value={data.completion_rate != null ? `${Math.round(data.completion_rate * 100)}%` : '—'}
        />
        <SummaryCard
          label="Priem. dĺžka hry"
          value={data.avg_game_duration_minutes != null ? `${Math.round(data.avg_game_duration_minutes)} min` : '—'}
        />
      </div>

      <div className={`grid gap-4 ${desktop ? 'grid-cols-2' : 'grid-cols-1'}`}>
        <TimeSeriesChart title="Hry za deň" data={data.games_per_day} />
        <TimeSeriesChart title="Nové registrácie za deň" data={data.players_per_day} />
        <TimeSeriesChart title="Odohrané kolá za deň" data={data.rounds_per_day} />
        <TimeSeriesChart title="Hodiny s najvyššou aktivitou" data={data.peak_hours} kind="bar" />
      </div>

      {/* Prepinac sa tyka len traffic-analytickych widgetov nizsie (PageView) --
          herne metriky vyssie su uz vzdy o prihlasenych uctoch. */}
      <ScopeToggle scope={scope} onChange={setScope} />

      <PageviewsChart
        total={data.pageviews_per_day}
        totalLabel={scope === 'logged_in' ? 'Prihlásení' : 'Zobrazenia'}
        visitors={data.visitors_per_day}
        visitorsLabel={scope === 'logged_in' ? 'Unikátní' : 'Návštevníci'}
        byDevice={data.pageviews_per_day_by_device}
        byBrowser={data.pageviews_per_day_by_browser}
        byOs={data.pageviews_per_day_by_os}
      />

      <div className={`grid gap-4 ${desktop ? 'grid-cols-2' : 'grid-cols-1'}`}>
        <BreakdownTable title="Najnavštevovanejšie stránky" data={data.top_paths} />
        <BreakdownTable title="Zdroje návštevnosti" data={data.top_referrers} />
        <BreakdownTable title="Prehliadače" data={data.browsers} />
        <BreakdownTable title="Operačné systémy" data={data.operating_systems} />
        <BreakdownTable title="Typ zariadenia" data={data.device_types} />
        <BreakdownTable title="Krajiny" data={data.countries} />
      </div>
    </div>
  );
}
