"use client";

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { ADMIN_REFRESH_EVENT } from '@/components/admin-nav';
import { downloadCsv } from '@/lib/csv';

interface RankingRow {
  city?: string;
  cnt: number;
}
interface CuisineRow {
  value: string;
  label: string;
  cnt: number;
}
interface ComboRow {
  city: string;
  cuisineLabel: string;
  cnt: number;
}
interface RestaurantRow {
  id: number;
  name: string;
  cuisine: string | null;
  city: string | null;
  cnt: number;
  is_sponsored: number;
}

interface StatsPayload {
  topCities: RankingRow[];
  topCitiesToday: RankingRow[];
  topCities7d: RankingRow[];
  topCities30d: RankingRow[];
  topCities365d: RankingRow[];
  sponsorInsights: {
    topCuisineMatchesToday: CuisineRow[];
    topCuisineMatches7d: CuisineRow[];
    topCuisineMatches30d: CuisineRow[];
    topCuisineMatches365d: CuisineRow[];
  };
  topCityCuisineCombos: ComboRow[];
  topCityCuisineCombosToday: ComboRow[];
  topCityCuisineCombos7d: ComboRow[];
  topCityCuisineCombos30d: ComboRow[];
  topCityCuisineCombos365d: ComboRow[];
  topRestaurants: RestaurantRow[];
  topRestaurantsToday: RestaurantRow[];
  topRestaurants7d: RestaurantRow[];
  topRestaurants30d: RestaurantRow[];
  topRestaurants365d: RestaurantRow[];
}

const RANK_COLORS = ['text-[#FFD700]', 'text-[#C0C0C0]', 'text-[#CD7F32]', 'text-adminmuted'];

function LeaderboardCard({
  title, badge, children,
}: { title: string; badge: string; children: React.ReactNode }) {
  return (
    <div className="glass p-6">
      <div className="flex items-center justify-between border-b-2 border-adminborder pb-2.5 mb-1">
        <p className="font-bold text-admintext text-[0.95em]">{title}</p>
        <span className="text-xs bg-adminbg px-2 py-1 rounded-full text-adminmuted font-normal">{badge}</span>
      </div>
      <ul className="list-none p-0 m-0">{children}</ul>
    </div>
  );
}

function LeaderboardItem({
  rank, title, subtitle, score, scoreLabel, progressPct, progressColor,
}: {
  rank: number;
  title: React.ReactNode;
  subtitle?: string;
  score: number | string;
  scoreLabel: string;
  progressPct?: number;
  progressColor?: string;
}) {
  return (
    <li className="flex items-center py-3 border-b border-[#f1f3f5] last:border-b-0">
      <div className={`w-8 text-lg font-extrabold ${RANK_COLORS[Math.min(rank - 1, 3)]}`}>
        {rank}
      </div>
      <div className="flex-grow pr-4">
        <div className="font-semibold text-admintext text-sm mb-1">{title}</div>
        {subtitle && <div className="text-xs text-adminmuted mb-1">{subtitle}</div>}
        {progressPct !== undefined && (
          <div className="w-full h-1.5 bg-adminborder rounded-full overflow-hidden mt-1">
            <div
              className="h-full rounded-full"
              style={{ width: `${progressPct}%`, background: progressColor ?? '#FE3C72' }}
            />
          </div>
        )}
      </div>
      <div className="text-right min-w-[70px]">
        <span className="font-bold text-[1.1em] text-admintext">{score}</span>
        <span className="block text-[0.65em] text-adminmuted uppercase font-normal">{scoreLabel}</span>
      </div>
    </li>
  );
}

export default function AdminRankingsPage() {
  const router = useRouter();
  const [stats, setStats] = useState<StatsPayload | null>(null);
  const [loading, setLoading] = useState(true);
  const [range, setRange] = useState<'today' | '7d' | '30d' | '365d'>('today');

  async function loadStats(force = false) {
    setLoading(true);
    try {
      const res = await fetch(force ? '/api/admin/stats?refresh=1' : '/api/admin/stats');
      if (res.status === 401) {
        router.push('/admin');
        return;
      }
      if (!res.ok) return;
      setStats(await res.json());
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => { loadStats(); }, []);

  useEffect(() => {
    const handleRefresh = () => loadStats(true);
    window.addEventListener(ADMIN_REFRESH_EVENT, handleRefresh);
    return () => window.removeEventListener(ADMIN_REFRESH_EVENT, handleRefresh);
  }, []);

  const topCitiesRange = {
    today: stats?.topCitiesToday ?? [],
    '7d': stats?.topCities7d ?? [],
    '30d': stats?.topCities30d ?? [],
    '365d': stats?.topCities365d ?? [],
  };
  const topCuisinesRange = {
    today: stats?.sponsorInsights.topCuisineMatchesToday ?? [],
    '7d': stats?.sponsorInsights.topCuisineMatches7d ?? [],
    '30d': stats?.sponsorInsights.topCuisineMatches30d ?? [],
    '365d': stats?.sponsorInsights.topCuisineMatches365d ?? [],
  };
  const topCityCuisineRange = {
    today: stats?.topCityCuisineCombosToday ?? [],
    '7d': stats?.topCityCuisineCombos7d ?? [],
    '30d': stats?.topCityCuisineCombos30d ?? [],
    '365d': stats?.topCityCuisineCombos365d ?? [],
  };
  const topRestaurantsRange = {
    today: stats?.topRestaurantsToday ?? [],
    '7d': stats?.topRestaurants7d ?? [],
    '30d': stats?.topRestaurants30d ?? [],
    '365d': stats?.topRestaurants365d ?? [],
  };

  const activeTopCities = topCitiesRange[range] ?? [];
  const activeTopCuisines = topCuisinesRange[range] ?? [];
  const activeCombos = topCityCuisineRange[range] ?? [];
  const activeRestaurants = topRestaurantsRange[range] ?? [];

  const topCitiesTotal = activeTopCities.reduce((sum, c) => sum + c.cnt, 0) ?? 0;
  const topCuisines = activeTopCuisines;
  const topCuisinesMax = topCuisines[0]?.cnt ?? 1;

  function handleExportCsv() {
    downloadCsv(
      `top-restaurants-${range}.csv`,
      ['Name', 'Stadt', 'Küche', 'Matches', 'Sponsor'],
      activeRestaurants.map((r) => [
        r.name,
        r.city ?? '',
        r.cuisine ?? '',
        r.cnt,
        r.is_sponsored === 1 ? 'Ja' : 'Nein',
      ]),
    );
  }

  return (
    <div className="p-6 lg:p-8 pb-24">
      <div className="max-w-6xl mx-auto">
        <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
          <p className="text-adminmuted text-sm">
            Deep-Dive in eure App-Daten: Entdecke die Favoriten deiner Nutzer, um Marketing und
            Sponsoren-Akquise gezielt zu steuern.
          </p>
          <div className="flex items-center gap-3">
            <button
              onClick={handleExportCsv}
              className="text-xs font-semibold text-admintext border border-adminborder bg-white px-4 py-1.5 rounded-full hover:bg-adminbg transition-colors"
            >
              CSV exportieren
            </button>
            <div className="flex items-center gap-2 rounded-full border border-adminborder bg-white p-1 text-xs">
              {(['today', '7d', '30d', '365d'] as const).map((option) => (
                <button
                  key={option}
                  onClick={() => setRange(option)}
                  className={`px-3 py-1.5 rounded-full transition-colors ${
                    range === option ? 'bg-yumder-pink text-white' : 'text-adminmuted'
                  }`}
                >
                  {option === 'today' ? 'Heute' : option === '7d' ? '7 Tage' : option === '30d' ? '30 Tage' : '365 Tage'}
                </button>
              ))}
            </div>
          </div>
        </div>

        {loading && !stats ? (
          <p className="text-adminmuted text-sm">Lade Rankings...</p>
        ) : stats ? (
          <div className="grid gap-4 md:grid-cols-2">
            <LeaderboardCard title="Top Städte" badge={`Nach Matches (${range === 'today' ? 'Heute' : range === '7d' ? '7 Tage' : range === '30d' ? '30 Tage' : '365 Tage'})`}>
              {activeTopCities.length === 0 && (
                <p className="text-sm text-adminmuted py-3">Noch keine Daten.</p>
              )}
              {activeTopCities.slice(0, 5).map((c, i) => {
                const pct = topCitiesTotal > 0 ? Math.round((c.cnt / topCitiesTotal) * 100) : 0;
                return (
                  <LeaderboardItem
                    key={c.city}
                    rank={i + 1}
                    title={
                      <span className="flex items-center justify-between">
                        <span>{c.city}</span>
                        <span className="text-xs text-adminmuted font-normal">{pct}% Anteil</span>
                      </span>
                    }
                    score={c.cnt}
                    scoreLabel="Matches"
                    progressPct={pct}
                  />
                );
              })}
            </LeaderboardCard>

            <LeaderboardCard title="Top Küchen-Kategorien" badge={`Nach Matches (${range === 'today' ? 'Heute' : range === '7d' ? '7 Tage' : range === '30d' ? '30 Tage' : '365 Tage'})`}>
              {topCuisines.length === 0 && (
                <p className="text-sm text-adminmuted py-3">Noch keine Daten.</p>
              )}
              {topCuisines.slice(0, 5).map((c, i) => (
                <LeaderboardItem
                  key={c.value}
                  rank={i + 1}
                  title={c.label}
                  score={c.cnt}
                  scoreLabel="Matches"
                  progressPct={Math.round((c.cnt / topCuisinesMax) * 100)}
                  progressColor="#4dabf7"
                />
              ))}
            </LeaderboardCard>

            <LeaderboardCard title="Beliebteste Kombinationen" badge="Stadt × Küche">
              {(!activeCombos || activeCombos.length === 0) && (
                <p className="text-sm text-adminmuted py-3">Noch keine Daten.</p>
              )}
              {activeCombos?.map((combo, i) => (
                <LeaderboardItem
                  key={`${combo.city}-${combo.cuisineLabel}`}
                  rank={i + 1}
                  title={
                    <span className="flex items-center gap-1.5">
                      <span className="inline-block bg-[#f1f3f5] border border-adminborder rounded px-2 py-0.5 text-[0.85em]">
                        {combo.city}
                      </span>
                      <span className="text-yumder-pink font-bold">×</span>
                      <span className="inline-block bg-[#f1f3f5] border border-adminborder rounded px-2 py-0.5 text-[0.85em]">
                        {combo.cuisineLabel}
                      </span>
                    </span>
                  }
                  score={combo.cnt}
                  scoreLabel="Matches"
                />
              ))}
            </LeaderboardCard>

            <LeaderboardCard title="Top Restaurants Leaderboard" badge={`Match-Häufigkeit (${range === 'today' ? 'Heute' : range === '7d' ? '7 Tage' : range === '30d' ? '30 Tage' : '365 Tage'})`}>
              {(!activeRestaurants || activeRestaurants.length === 0) && (
                <p className="text-sm text-adminmuted py-3">Noch keine Daten.</p>
              )}
              {activeRestaurants?.map((r, i) => (
                <LeaderboardItem
                  key={r.id}
                  rank={i + 1}
                  title={
                    <span>
                      {r.name}
                      {r.is_sponsored === 1 && (
                        <span className="text-xs text-adminsuccess ml-1.5 font-normal">Sponsor</span>
                      )}
                    </span>
                  }
                  subtitle={[r.city, r.cuisine].filter(Boolean).join(' · ') || undefined}
                  score={r.cnt}
                  scoreLabel="Matches"
                />
              ))}
            </LeaderboardCard>
          </div>
        ) : (
          <p className="text-adminmuted text-sm">Rankings nicht verfügbar.</p>
        )}
      </div>
    </div>
  );
}
