import { useEffect, useState } from 'react';
import { Database, HardDrive, Radio, Scale } from 'lucide-react';
import { PageHeader } from '@/components/ui/PageHeader';
import { Card, CardBody, CardHeader } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import { fmt as tfmt, plural, useT, type Dict } from '@/lib/i18n';

interface LakeStats {
  bytes: number; events: number; matchesParsed: number; players: number;
  eventFiles: number; competitionSeasons: number; nationalTeamsCovered: number; generatedAt: string;
}
interface DataStats {
  lake: LakeStats | null;
  archive: { results: number; asOf: string; h2hPairings: number } | null;
  fingerprints: number | null;
  squadValues: number | null;
  db: Record<string, number>;
  sources: { source: string; last_ok: number | null; consec_fail: number; open_until: number }[];
}

const fmt = (n: number) => n.toLocaleString();
const gb = (b: number) => `${(b / 1e9).toFixed(2)} GB`;
const ago = (t: number | null, d: Dict) => {
  if (!t) return d.common.never;
  const m = Math.round((Date.now() - t) / 60000);
  return m < 1 ? d.common.justNow : m < 60 ? tfmt(d.common.minAgo, { n: m }) : tfmt(d.common.hoursAgo, { n: Math.round(m / 60) });
};

function Big({ value, label }: { value: string; label: string }) {
  return (
    <div className="text-center">
      <div className="font-display text-3xl font-extrabold text-accent">{value}</div>
      <div className="mt-0.5 text-[11px] uppercase tracking-wide text-faint">{label}</div>
    </div>
  );
}

function Counter({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between border-b border-line/60 py-1.5 text-sm last:border-0">
      <span className="text-muted">{label}</span>
      <span className="tnum font-semibold text-ink">{value}</span>
    </div>
  );
}

export function DataPage() {
  const t = useT();
  const [stats, setStats] = useState<DataStats | null>(null);

  useEffect(() => {
    let alive = true;
    fetch('/api/data/stats').then((r) => r.json()).then((d: DataStats) => alive && setStats(d)).catch(() => {});
    return () => { alive = false; };
  }, []);

  if (!stats) return <div className="h-96 animate-pulse rounded-xl border border-line bg-panel" />;
  const lake = stats.lake;

  return (
    <div className="space-y-5">
      <PageHeader
        title={t.data.title}
        subtitle={t.data.subtitle}
      />

      {lake && (
        <Card>
          <CardHeader className="flex items-center gap-2">
            <HardDrive size={16} className="text-accent" />
            <span className="font-display font-bold text-ink">{t.data.lake.heading}</span>
            <Badge tone="muted">{tfmt(t.data.lake.openDataBadge, { provider: 'StatsBomb' })}</Badge>
          </CardHeader>
          <CardBody>
            <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
              <Big value={gb(lake.bytes)} label={t.data.lake.parsed} />
              <Big value={`${(lake.events / 1e6).toFixed(1)}M`} label={t.data.lake.events} />
              <Big value={fmt(lake.matchesParsed)} label={t.data.lake.matches} />
              <Big value={fmt(lake.players)} label={t.data.lake.players} />
            </div>
            <p className="mt-4 text-sm text-muted">
              {tfmt(t.data.lake.summary, { seasons: lake.competitionSeasons, covered: lake.nationalTeamsCovered, total: 48 })}
            </p>
          </CardBody>
        </Card>
      )}

      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader className="flex items-center gap-2">
            <Database size={16} className="text-accent" />
            <span className="font-display font-bold text-ink">{t.data.archive.heading}</span>
          </CardHeader>
          <CardBody>
            {stats.archive && (
              <>
                <Counter label={t.data.archive.internationalResults} value={fmt(stats.archive.results)} />
                <Counter label={t.data.archive.h2hPairings} value={fmt(stats.archive.h2hPairings)} />
                <Counter label={t.data.archive.ratingsThrough} value={stats.archive.asOf} />
              </>
            )}
            {stats.squadValues != null && <Counter label={tfmt(t.data.archive.squadValues, { provider: 'Transfermarkt' })} value={plural(t.data.archive.teamsCount, stats.squadValues)} />}
            {stats.fingerprints != null && <Counter label={t.data.archive.fingerprints} value={plural(t.data.archive.teamsCount, stats.fingerprints)} />}
          </CardBody>
        </Card>

        <Card>
          <CardHeader className="flex items-center gap-2">
            <Radio size={16} className="text-accent" />
            <span className="font-display font-bold text-ink">{t.data.live.heading}</span>
          </CardHeader>
          <CardBody>
            <Counter label={t.data.live.oddsLines} value={fmt(stats.db.oddsLines ?? 0)} />
            <Counter label={t.data.live.oddsFixtures} value={fmt(stats.db.oddsFixtures ?? 0)} />
            <Counter label={t.data.live.frozenForecasts} value={fmt(stats.db.frozenForecasts ?? 0)} />
            <Counter label={t.data.live.enrichedMatches} value={fmt(stats.db.enrichedMatches ?? 0)} />
            <Counter label={t.data.live.cachedResponses} value={fmt(stats.db.cachedResponses ?? 0)} />
            <Counter label={t.data.live.ingestRuns} value={fmt(stats.db.ingestEvents ?? 0)} />
          </CardBody>
        </Card>
      </div>

      <Card>
        <CardHeader className="flex items-center gap-2">
          <Scale size={16} className="text-accent" />
          <span className="font-display font-bold text-ink">{t.data.sources.heading}</span>
        </CardHeader>
        <CardBody>
          {stats.sources.length ? stats.sources.map((s) => (
            <div key={s.source} className="flex items-center justify-between border-b border-line/60 py-1.5 text-sm last:border-0">
              <span className="font-medium text-ink">{s.source}</span>
              <span className="flex items-center gap-2">
                {s.open_until > Date.now() ? (
                  <Badge tone="muted">{t.data.sources.paused}</Badge>
                ) : s.consec_fail > 0 ? (
                  <Badge tone="gold">{plural(t.data.sources.recentFailures, s.consec_fail)}</Badge>
                ) : (
                  <Badge tone="accent">{t.data.sources.healthy}</Badge>
                )}
                <span className="text-xs text-faint">{tfmt(t.data.sources.lastOk, { time: ago(s.last_ok, t) })}</span>
              </span>
            </div>
          )) : <p className="text-sm text-faint">{t.data.sources.empty}</p>}
          <p className="mt-3 border-t border-line pt-2 text-xs text-faint">
            {t.data.sources.footer.label} openfootball ({t.data.sources.footer.roleFixtures}) · ESPN ({t.data.sources.footer.roleLiveScores}) · football-data.org ({t.data.sources.footer.roleFallback}) ·
            martj42 ({t.data.sources.footer.roleResultsArchive}) · StatsBomb ({t.data.sources.footer.roleOpenData}) · Transfermarkt ({t.data.sources.footer.roleSquadValues}). {t.data.sources.footer.note}
          </p>
        </CardBody>
      </Card>
    </div>
  );
}
