"use client";

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Bar, Doughnut } from 'react-chartjs-2';
import {
  Chart as ChartJS, CategoryScale, LinearScale, BarElement, ArcElement,
  PointElement, LineElement, Tooltip, Legend, Filler,
} from 'chart.js';
import { ADMIN_REFRESH_EVENT } from '@/components/admin-nav';
import { formatLabelInTz, REPORTING_TZ } from '@/lib/timezone';

ChartJS.register(
  CategoryScale, LinearScale, BarElement, ArcElement,
  PointElement, LineElement, Tooltip, Legend, Filler,
);

interface SponsorInsightRow {
  city?: string;
  value?: string;
  label?: string;
  cnt: number;
}

interface StatsPayload {
  sponsorInsights: {
    topCitiesMatchesToday: SponsorInsightRow[];
    topCitiesMatches7d: SponsorInsightRow[];
    topCitiesMatches30d: SponsorInsightRow[];
    topCitiesMatches365d: SponsorInsightRow[];
    topCuisineMatchesToday: SponsorInsightRow[];
    topCuisineMatches7d: SponsorInsightRow[];
    topCuisineMatches30d: SponsorInsightRow[];
    topCuisineMatches365d: SponsorInsightRow[];
  };
  swipeVolumeToday: { labels: string[]; data: number[] };
  swipeVolume7d: { labels: string[]; data: number[] };
  swipeVolume30d: { labels: string[]; data: number[] };
  swipeVolume365d: { labels: string[]; data: number[] };
  swipeRatioByCuisine: { value: string; label: string; yesPct: number; total: number }[];
  sponsorVsOrganic: { sponsored: number; total: number; pct: number };
}

function InsightList({
  title, rows, unit, accent = 'pink',
}: {
  title: string;
  rows: SponsorInsightRow[];
  unit: string;
  accent?: 'pink' | 'teal';
}) {
  const chipCls =
    accent === 'teal'
      ? 'bg-yumder-teal/15 text-yumder-teal border-yumder-teal/30'
      : 'bg-yumder-pink/15 text-yumder-pink border-yumder-pink/30';
  return (
    <div className="glass p-6">
      <p className="text-xs text-adminmuted uppercase tracking-wide font-bold mb-3">{title}</p>
      {rows.length === 0 ? (
        <p className="text-sm text-adminmuted">Noch keine Matches in diesem Zeitraum.</p>
      ) : (
        <div className="flex flex-wrap gap-2">
          {rows.map((r) => (
            <span
              key={(r.city || r.value || '') + r.cnt}
              className={`text-sm border rounded-full px-3 py-1 ${chipCls}`}
            >
              {r.city || r.label || r.value}{' '}
              <span className="font-semibold tabular-nums">
                {r.cnt} {unit}
              </span>
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

export default function AdminInsightsPage() {
  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 SI = stats?.sponsorInsights;
  const cities =
    range === 'today'
      ? SI?.topCitiesMatchesToday
      : range === '7d'
        ? SI?.topCitiesMatches7d
        : range === '30d'
          ? SI?.topCitiesMatches30d
          : SI?.topCitiesMatches365d;
  const cuisine =
    range === 'today'
      ? SI?.topCuisineMatchesToday
      : range === '7d'
        ? SI?.topCuisineMatches7d
        : range === '30d'
          ? SI?.topCuisineMatches30d
          : SI?.topCuisineMatches365d;

  const kitchenChartData = stats?.swipeRatioByCuisine ?? [];
  const swipeTrend =
    range === 'today'
      ? stats?.swipeVolumeToday
      : range === '7d'
        ? stats?.swipeVolume7d
        : range === '30d'
          ? stats?.swipeVolume30d
          : stats?.swipeVolume365d;
  const sponsorVsOrganic = stats?.sponsorVsOrganic;

  return (
    <div className="p-6 lg:p-8 pb-24">
      <div className="max-w-6xl mx-auto">
        <div className="flex flex-wrap items-end justify-between gap-3 mb-3">
          <div>
            <h2 className="text-lg font-semibold text-admintext">Sponsor-Insights</h2>
            <p className="text-xs text-adminmuted">
              Matches nach Stadt und Küche — als Verkaufsargument für Sponsoring-Anfragen.
            </p>
          </div>
          <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>

        {loading && !stats ? (
          <p className="text-adminmuted text-sm">Lade Insights...</p>
        ) : stats ? (
          <div className="flex flex-col gap-4">
            <div className="grid gap-4 lg:grid-cols-2">
              <div className="glass p-6">
                <p className="text-xs text-adminmuted uppercase tracking-wide font-bold mb-3">
                  Swipe-Ratio "Ja" nach Küche (Top 6, Lifetime)
                </p>
                <div className="h-64">
                  {kitchenChartData.length > 0 ? (
                    <Doughnut
                      data={{
                        labels: kitchenChartData.map((c) => c.label),
                        datasets: [{
                          label: 'Swipes',
                          data: kitchenChartData.map((c) => c.total),
                          backgroundColor: ['#FE3C72', '#FF8AA7', '#F39A9A', '#F7C3D9', '#F7B267', '#F9D5A7'],
                          borderColor: '#ffffff',
                          borderWidth: 2,
                        }],
                      }}
                      options={{
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                          legend: { position: 'bottom', labels: { usePointStyle: true, boxWidth: 8 } },
                          tooltip: {
                            callbacks: {
                              label: (ctx) => `${ctx.label}: ${ctx.parsed} Swipes (${kitchenChartData[ctx.dataIndex]?.yesPct ?? 0}% Ja)`,
                            },
                          },
                        },
                      }}
                    />
                  ) : (
                    <p className="text-sm text-adminmuted">Noch nicht genug Swipe-Daten pro Küche.</p>
                  )}
                </div>
              </div>

              <div className="glass p-6">
                <p className="text-xs text-adminmuted uppercase tracking-wide font-bold mb-3">
                  Swipe-Volumen ({range === 'today' ? 'heute nach Stunden' : range === '7d' ? '7 Tage' : range === '30d' ? '30 Tage' : '365 Tage'})
                </p>
                <div className="h-64">
                  {swipeTrend && swipeTrend.data.some((v) => v > 0) ? (
                    <Bar
                      data={{
                        labels: swipeTrend.labels.map((label) => {
                          if (range === 'today') return label.replace(':00', '');
                          if (range === '365d') return formatLabelInTz(label, REPORTING_TZ, { month: 'short' });
                          return formatLabelInTz(label, REPORTING_TZ, { day: '2-digit', month: '2-digit' });
                        }),
                        datasets: [{
                          label: 'Swipes',
                          data: swipeTrend.data,
                          backgroundColor: range === 'today' ? '#ff7aa6' : '#FE3C72',
                          borderRadius: 6,
                        }],
                      }}
                      options={{
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: { legend: { display: false } },
                        scales: {
                          x: {
                            grid: { display: false },
                            ticks: {
                              maxRotation: 0,
                              autoSkip: range === 'today',
                              maxTicksLimit: range === 'today' ? 12 : 7,
                            },
                          },
                          y: { beginAtZero: true, grid: { color: '#e9ecef' } },
                        },
                      }}
                    />
                  ) : (
                    <p className="text-sm text-adminmuted self-center">Noch keine Swipe-Daten.</p>
                  )}
                </div>
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-3">
              <InsightList
                title={`Top-Städte nach Matches (${range === 'today' ? 'heute' : range === '7d' ? '7 Tage' : range === '30d' ? '30 Tage' : '365 Tage'})`}
                rows={cities || []}
                unit="Matches"
                accent="pink"
              />
              <InsightList
                title={`Top-Küchen nach Matches (${range === 'today' ? 'heute' : range === '7d' ? '7 Tage' : range === '30d' ? '30 Tage' : '365 Tage'})`}
                rows={cuisine || []}
                unit="Matches"
                accent="teal"
              />

              <div className="glass p-6">
                <p className="text-xs text-adminmuted uppercase tracking-wide font-bold mb-3">
                  Sponsor vs. Organisch
                </p>
                {sponsorVsOrganic && sponsorVsOrganic.total > 0 ? (
                  <div className="mt-2">
                    <div className="flex justify-between text-sm mb-1.5">
                      <span className="text-adminmuted">Sponsor-Restaurants in Matches</span>
                      <strong className="text-admintext">{sponsorVsOrganic.sponsored} von {sponsorVsOrganic.total} ({sponsorVsOrganic.pct}%)</strong>
                    </div>
                    <div className="w-full h-2 bg-adminborder rounded-full overflow-hidden">
                      <div
                        className="h-full bg-yumder-pink rounded-full"
                        style={{ width: `${sponsorVsOrganic.pct}%` }}
                      />
                    </div>
                  </div>
                ) : (
                  <p className="text-sm text-adminmuted">Noch keine Matches vorhanden.</p>
                )}
                <p className="text-xs text-adminmuted mt-4 leading-relaxed">
                  Tipp: Sponsoren mit hoher "Nein"-Quote brauchen evtl. bessere Bilder.
                </p>
              </div>
            </div>
          </div>
        ) : (
          <p className="text-adminmuted text-sm">Insights nicht verfügbar.</p>
        )}
      </div>
    </div>
  );
}
