"use client";

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { motion } from 'motion/react';
import { CUISINE_OPTIONS } from '@/lib/cuisine';
import { ADMIN_REFRESH_EVENT } from '@/components/admin-nav';
import { SponsorFormModal } from '@/components/sponsor-form-modal';
import { downloadCsv } from '@/lib/csv';

interface Sponsor {
  id: number;
  restaurant_id: number | null;
  name: string;
  image_url: string | null;
  address: string | null;
  city: string | null;
  postal_code: string | null;
  lat: number | null;
  lon: number | null;
  filter_cuisine_tags: string | null;
  discount_text: string | null;
  priority: number;
  active: number;
  active_from: string | null;
  active_until: string | null;
  impressions: number;
  yesSwipes: number;
  matches: number;
}

function boostLabelFromPriority(priority: number): string {
  if (priority >= 8) return 'Boost 3x';
  if (priority >= 4) return 'Boost 2x';
  return 'Boost 1x';
}

function cuisineLabelFromTags(tagsJson: string | null): string {
  if (!tagsJson) return 'Ohne Kategorie';
  try {
    const tags: string[] = JSON.parse(tagsJson);
    if (tags.length === 0) return 'Ohne Kategorie';
    const opt = CUISINE_OPTIONS.find((o) => o.value === tags[0]);
    return opt?.label ?? tags[0];
  } catch {
    return 'Ohne Kategorie';
  }
}

function isExpired(activeUntil: string | null): boolean {
  if (!activeUntil) return false;
  return new Date(activeUntil) < new Date();
}

function daysUntil(dateStr: string): number {
  const diff = new Date(dateStr).getTime() - Date.now();
  return Math.ceil(diff / (1000 * 60 * 60 * 24));
}

function formatDateDe(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('de-DE');
}

export default function AdminSponsorsPage() {
  const router = useRouter();
  const [sponsors, setSponsors] = useState<Sponsor[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [sponsorToEdit, setSponsorToEdit] = useState<Sponsor | null>(null);

  async function loadSponsors() {
    setLoading(true);
    try {
      const res = await fetch('/api/admin/sponsors');
      if (res.status === 401) {
        router.push('/admin');
        return;
      }
      const data = await res.json();
      setSponsors(data.sponsors);
    } finally {
      setLoading(false);
    }
  }

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

  useEffect(() => {
    window.addEventListener(ADMIN_REFRESH_EVENT, loadSponsors);
    return () => window.removeEventListener(ADMIN_REFRESH_EVENT, loadSponsors);
  }, []);

  function openCreateForm() {
    setSponsorToEdit(null);
    setShowForm(true);
  }

  function openEditForm(s: Sponsor) {
    setSponsorToEdit(s);
    setShowForm(true);
  }

  async function handleDelete(id: number) {
    if (!confirm('Diesen gesponserten Eintrag wirklich loeschen?')) return;
    await fetch(`/api/admin/sponsors/${id}`, { method: 'DELETE' });
    loadSponsors();
  }

  async function handleTogglePause(s: Sponsor) {
    await fetch(`/api/admin/sponsors/${s.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        name: s.name, imageUrl: s.image_url, address: s.address, city: s.city, postalCode: s.postal_code,
        lat: s.lat, lon: s.lon,
        filterCuisineTags: s.filter_cuisine_tags ? JSON.parse(s.filter_cuisine_tags) : [],
        discountText: s.discount_text, priority: s.priority,
        active: s.active !== 1,
        activeFrom: s.active_from, activeUntil: s.active_until,
        restaurantId: s.restaurant_id,
      }),
    });
    loadSponsors();
  }

  function handleExportCsv() {
    downloadCsv(
      'sponsoren.csv',
      ['Name', 'PLZ', 'Stadt', 'Küche', 'Boost', 'Status', 'Swipes', 'Ja-Swipes', 'Matches', 'Läuft bis'],
      sponsors.map((s) => [
        s.name,
        s.postal_code ?? '',
        s.city ?? '',
        cuisineLabelFromTags(s.filter_cuisine_tags),
        boostLabelFromPriority(s.priority),
        isExpired(s.active_until) ? 'Abgelaufen' : s.active === 1 ? 'Aktiv' : 'Pausiert',
        s.impressions,
        s.yesSwipes,
        s.matches,
        s.active_until ? formatDateDe(s.active_until) : '',
      ]),
    );
  }

  return (
    <div className="p-6 lg:p-8 pb-24">
      <div className="max-w-6xl mx-auto">
        <div className="flex flex-wrap items-center justify-between gap-3 mb-1">
          <div>
            <h3 className="text-lg font-semibold text-admintext mb-1">Aktive Kampagnen</h3>
            <p className="text-adminmuted text-sm m-0">
              Verwalte hier gesponserte Restaurants und ihre Swipe-Karten.
            </p>
          </div>
          <div className="flex items-center gap-3">
            <button
              onClick={handleExportCsv}
              disabled={sponsors.length === 0}
              className="text-sm font-semibold text-admintext border border-adminborder bg-white px-4 py-2.5 rounded-lg hover:bg-adminbg transition-colors disabled:opacity-40"
            >
              CSV exportieren
            </button>
            <button
              onClick={openCreateForm}
              className="bg-yumder-pink text-white font-semibold text-sm px-5 py-2.5 rounded-lg hover:opacity-90 transition-opacity"
            >
              + Neue Kampagne anlegen
            </button>
          </div>
        </div>

        {loading ? (
          <p className="text-adminmuted mt-6">Lade Sponsoren...</p>
        ) : sponsors.length === 0 ? (
          <p className="text-adminmuted mt-6">Noch keine gesponserten Restaurants angelegt.</p>
        ) : (
          <div className="grid gap-6 mt-5" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))' }}>
            {sponsors.map((s) => {
              const expired = isExpired(s.active_until);
              const statusLabel = expired ? 'Abgelaufen' : s.active === 1 ? 'Aktiv' : 'Pausiert';
              const statusCls =
                expired || s.active !== 1
                  ? 'bg-adminmuted'
                  : 'bg-adminsuccess';
              return (
                <motion.div
                  key={s.id}
                  layout
                  initial={{ opacity: 0, y: 8 }}
                  animate={{ opacity: 1, y: 0 }}
                  className={`glass overflow-hidden hover:shadow-xl transition-shadow ${
                    expired ? 'opacity-70' : ''
                  }`}
                >
                  <Link href={`/admin/dashboard/sponsors/${s.id}`} className="block">
                    <div className="relative w-full h-40 bg-adminborder rounded-t-3xl overflow-hidden">
                      {s.image_url ? (
                        <img
                          src={s.image_url}
                          alt={s.name}
                          className="w-full h-full object-cover"
                          onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }}
                        />
                      ) : (
                        <div className="w-full h-full flex items-center justify-center text-adminmuted text-sm">
                          Kein Bild
                        </div>
                      )}
                      <span
                        className={`absolute top-3 right-3 px-3 py-1 rounded-full text-xs font-bold text-white shadow-[0_8px_20px_-4px_rgba(254,60,114,0.55)] ${statusCls}`}
                      >
                        {statusLabel}
                      </span>
                    </div>
                  </Link>

                  <div className="p-6">
                    <Link href={`/admin/dashboard/sponsors/${s.id}`} className="block hover:opacity-80 transition-opacity">
                      <h4 className={`text-lg font-bold mb-1 ${expired ? 'text-adminmuted' : 'text-admintext'}`}>
                        {s.name}
                      </h4>
                    </Link>
                    <p className="text-sm text-adminmuted mb-1">
                      {[s.postal_code, s.city].filter(Boolean).join(' ') || '–'} • {cuisineLabelFromTags(s.filter_cuisine_tags)} • {boostLabelFromPriority(s.priority)}
                    </p>
                    <p className={`text-xs mb-4 font-semibold ${s.restaurant_id ? 'text-yumder-teal' : 'text-adminmuted'}`}>
                      {s.restaurant_id ? 'Mit Restaurant-Daten verknüpft' : 'Nicht verknüpft (keine Live-Stats)'}
                    </p>

                    <div className={`flex justify-between bg-adminbg p-3 rounded-lg mb-4 border border-adminborder text-sm ${expired ? 'opacity-60' : ''}`}>
                      <div className="text-center flex-1">
                        <span className="block font-bold text-[1.3em] text-blue-600 mb-0.5">{s.impressions}</span>
                        <span className="text-xs text-adminmuted">Swipes</span>
                      </div>
                      <div className="text-center flex-1">
                        <span className="block font-bold text-[1.3em] text-adminsuccess mb-0.5">{s.yesSwipes}</span>
                        <span className="text-xs text-adminmuted">"Ja" Swipes</span>
                      </div>
                      <div className="text-center flex-1">
                        <span className="block font-bold text-[1.3em] text-yumder-teal mb-0.5">{s.matches}</span>
                        <span className="text-xs text-adminmuted">Matches</span>
                      </div>
                    </div>

                    {s.active_until && (
                      <p
                        className={`text-xs mb-4 text-center font-semibold ${
                          expired ? 'text-admindanger' : 'text-adminmuted'
                        }`}
                      >
                        {expired
                          ? `Abgelaufen am ${formatDateDe(s.active_until)}`
                          : `Läuft bis: ${formatDateDe(s.active_until)} (Noch ${daysUntil(s.active_until)} Tage)`}
                      </p>
                    )}

                    <Link
                      href={`/admin/dashboard/sponsors/${s.id}`}
                      className="block mb-2.5 py-2.5 text-center bg-yumder-teal text-white rounded-lg font-semibold text-sm hover:opacity-90 transition-opacity"
                    >
                      Anzeigen
                    </Link>

                    <div className="flex gap-2.5">
                      {expired ? (
                        <button
                          onClick={() => openEditForm(s)}
                          className="flex-1 py-2.5 border border-adminsuccess text-adminsuccess bg-white rounded-lg font-semibold text-sm hover:bg-green-50 transition-colors"
                        >
                          Neu auflegen
                        </button>
                      ) : (
                        <>
                          <button
                            onClick={() => openEditForm(s)}
                            className="flex-1 py-2.5 border border-yumder-pink text-yumder-pink bg-white rounded-lg font-semibold text-sm hover:bg-pink-50 transition-colors"
                          >
                            Bearbeiten
                          </button>
                          <button
                            onClick={() => handleTogglePause(s)}
                            className="flex-1 py-2.5 border border-adminborder text-admintext bg-white rounded-lg font-semibold text-sm hover:bg-adminbg transition-colors"
                          >
                            {s.active === 1 ? 'Pausieren' : 'Aktivieren'}
                          </button>
                        </>
                      )}
                    </div>
                    <button
                      onClick={() => handleDelete(s.id)}
                      className="w-full mt-2 text-xs text-admindanger hover:underline"
                    >
                      Löschen
                    </button>
                  </div>
                </motion.div>
              );
            })}
          </div>
        )}

        {showForm && (
          <SponsorFormModal
            sponsorToEdit={sponsorToEdit}
            onClose={() => setShowForm(false)}
            onSaved={loadSponsors}
          />
        )}
      </div>
    </div>
  );
}
