import React from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { ArrowLeft, Camera, Heart, Loader2, RefreshCw, Sparkles, QrCode } from 'lucide-react';

import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';

import { AdminLayout } from '../components/AdminLayout';
import {
  EventStats as TenantEventStats,
  getEvent,
  getEventStats,
  TenantEvent,
  toggleEvent,
} from '../api';
import { isAuthError } from '../auth/tokens';
import {
  ADMIN_EVENTS_PATH,
  ADMIN_EVENT_EDIT_PATH,
  ADMIN_EVENT_PHOTOS_PATH,
  ADMIN_EVENT_MEMBERS_PATH,
  ADMIN_EVENT_TASKS_PATH,
  ADMIN_EVENT_TOOLKIT_PATH,
  ADMIN_EVENT_INVITES_PATH,
} from '../constants';

interface State {
  event: TenantEvent | null;
  stats: TenantEventStats | null;
  error: string | null;
  loading: boolean;
  busy: boolean;
}

export default function EventDetailPage() {
  const params = useParams<{ slug?: string }>();
  const [searchParams] = useSearchParams();
  const slug = params.slug ?? searchParams.get('slug') ?? null;
  const navigate = useNavigate();

  const [state, setState] = React.useState<State>({
    event: null,
    stats: null,
    error: null,
    loading: true,
    busy: false,
  });

  const load = React.useCallback(async () => {
    if (!slug) {
      setState((prev) => ({ ...prev, loading: false, error: 'Kein Event-Slug angegeben.' }));
      return;
    }

    setState((prev) => ({ ...prev, loading: true, error: null }));
    try {
      const [eventData, statsData] = await Promise.all([
        getEvent(slug),
        getEventStats(slug),
      ]);
      setState((prev) => ({
        ...prev,
        event: eventData,
        stats: statsData,
        loading: false,
      }));
    } catch (err) {
      if (isAuthError(err)) return;
      setState((prev) => ({ ...prev, error: 'Event konnte nicht geladen werden.', loading: false }));
    }
  }, [slug]);

  React.useEffect(() => {
    load();
  }, [load]);

  async function handleToggle() {
    if (!slug) return;
    setState((prev) => ({ ...prev, busy: true, error: null }));
    try {
      const updated = await toggleEvent(slug);
      setState((prev) => ({
        ...prev,
        event: updated,
        stats: prev.stats ? { ...prev.stats, status: updated.status, is_active: Boolean(updated.is_active) } : prev.stats,
        busy: false,
      }));
    } catch (err) {
      if (!isAuthError(err)) {
        setState((prev) => ({ ...prev, error: 'Status konnte nicht angepasst werden.', busy: false }));
      } else {
        setState((prev) => ({ ...prev, busy: false }));
      }
    }
  }

  const { event, stats, error, loading, busy } = state;
  const eventDisplayName = event ? renderName(event.name) : '';
  const activeInvitesCount = event?.active_invites_count ?? 0;
  const totalInvitesCount = event?.total_invites_count ?? activeInvitesCount;

  const actions = (
    <>
      <Button
        variant="outline"
        onClick={() => navigate(ADMIN_EVENTS_PATH)}
        className="border-pink-200 text-pink-600 hover:bg-pink-50"
      >
        <ArrowLeft className="h-4 w-4" /> Zurück zur Liste
      </Button>
      {event && (
        <>
          <Button
            variant="outline"
            onClick={() => navigate(ADMIN_EVENT_EDIT_PATH(event.slug))}
            className="border-fuchsia-200 text-fuchsia-700 hover:bg-fuchsia-50"
          >
            Bearbeiten
          </Button>
          <Button
            variant="outline"
            onClick={() => navigate(ADMIN_EVENT_MEMBERS_PATH(event.slug))}
            className="border-sky-200 text-sky-700 hover:bg-sky-50"
          >
            Mitglieder
          </Button>
          <Button
            variant="outline"
            onClick={() => navigate(ADMIN_EVENT_TASKS_PATH(event.slug))}
            className="border-amber-200 text-amber-600 hover:bg-amber-50"
          >
            Tasks
          </Button>
          <Button
            variant="outline"
            onClick={() => navigate(ADMIN_EVENT_INVITES_PATH(event.slug))}
            className="border-amber-200 text-amber-600 hover:bg-amber-50"
          >
            QR &amp; Einladungen
          </Button>
          <Button
            variant="outline"
            onClick={() => navigate(ADMIN_EVENT_TOOLKIT_PATH(event.slug))}
            className="border-emerald-200 text-emerald-600 hover:bg-emerald-50"
          >
            Event-Day Toolkit
          </Button>
        </>
      )}
    </>
  );

  if (!slug) {
    return (
      <AdminLayout title="Event nicht gefunden" subtitle="Bitte wähle ein Event aus der Übersicht." actions={actions}>
        <Card className="border-0 bg-white/85 shadow-xl shadow-pink-100/60">
          <CardContent className="p-6 text-sm text-slate-600">
            Ohne gültigen Slug können wir keine Daten laden. Kehre zur Event-Liste zurück und wähle dort ein Event aus.
          </CardContent>
        </Card>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout
      title={event ? renderName(event.name) : 'Event wird geladen'}
      subtitle="Verwalte Status, Einladungen und Statistiken deines Events."
      actions={actions}
    >
      {error && (
        <Alert variant="destructive">
          <AlertTitle>Aktion fehlgeschlagen</AlertTitle>
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      {loading ? (
        <DetailSkeleton />
      ) : event ? (
        <div className="grid gap-6 lg:grid-cols-[2fr,1fr]">
          <Card className="border-0 bg-white/90 shadow-xl shadow-pink-100/60">
            <CardHeader className="space-y-2">
              <CardTitle className="flex items-center gap-2 text-xl text-slate-900">
                <Sparkles className="h-5 w-5 text-pink-500" /> Eventdaten
              </CardTitle>
              <CardDescription className="text-sm text-slate-600">
                Grundlegende Informationen für Gäste und Moderation.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4 text-sm text-slate-700">
              <InfoRow label="Slug" value={event.slug} />
              <InfoRow label="Status" value={event.status === 'published' ? 'Veröffentlicht' : event.status} />
              <InfoRow label="Datum" value={formatDate(event.event_date)} />
              <InfoRow label="Aktiv" value={event.is_active ? 'Aktiv' : 'Deaktiviert'} />
              <div className="flex flex-wrap gap-3 pt-2">
                <Button
                  onClick={handleToggle}
                  disabled={busy}
                  className="bg-gradient-to-r from-pink-500 via-fuchsia-500 to-purple-500 text-white shadow-lg shadow-pink-500/20"
                >
                  {busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
                  {event.is_active ? 'Deaktivieren' : 'Aktivieren'}
                </Button>
                <Button
                  variant="outline"
                  onClick={() => navigate(ADMIN_EVENT_PHOTOS_PATH(event.slug))}
                  className="border-sky-200 text-sky-700 hover:bg-sky-50"
                >
                  <Camera className="h-4 w-4" /> Fotos moderieren
                </Button>
              </div>
            </CardContent>
          </Card>

          <Card className="border-0 bg-white/90 shadow-xl shadow-amber-100/60">
            <CardHeader className="space-y-2">
              <CardTitle className="flex items-center gap-2 text-xl text-slate-900">
                <QrCode className="h-5 w-5 text-amber-500" /> Einladungen &amp; QR
              </CardTitle>
              <CardDescription className="text-sm text-slate-600">
                Steuere QR-Einladungen, Layouts und Branding gesammelt auf einer eigenen Seite.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4 text-sm text-slate-700">
              <div className="space-y-2 rounded-xl border border-amber-100 bg-amber-50/70 p-3 text-xs text-amber-800">
                <p>
                  Aktive QR-Einladungen: {activeInvitesCount} · Gesamt erstellt: {totalInvitesCount}
                </p>
                <p>
                  Bereite deine Drucklayouts vor, personalisiere Texte und Logos und drucke sie direkt aus.
                </p>
              </div>

              <div className="space-y-2">
                <Button
                  className="w-full bg-amber-500 text-white shadow-lg shadow-amber-500/20 hover:bg-amber-500/90"
                  onClick={() => navigate(ADMIN_EVENT_INVITES_PATH(event.slug))}
                >
                  Einladungen &amp; Layouts verwalten
                </Button>
                <p className="text-xs text-slate-500">
                  Du kannst bestehende Layouts duplizieren, Farben anpassen und neue PDFs generieren.
                </p>
              </div>
            </CardContent>
          </Card>

          <Card className="border-0 bg-white/90 shadow-xl shadow-sky-100/60 lg:col-span-2">
            <CardHeader className="space-y-2">
              <CardTitle className="flex items-center gap-2 text-xl text-slate-900">
                <Heart className="h-5 w-5 text-sky-500" /> Performance
              </CardTitle>
              <CardDescription className="text-sm text-slate-600">
                Kennzahlen zu Uploads, Highlights und Interaktion.
              </CardDescription>
            </CardHeader>
            <CardContent className="grid gap-3 sm:grid-cols-2 md:grid-cols-4">
              <StatChip label="Fotos" value={stats?.total ?? 0} />
              <StatChip label="Featured" value={stats?.featured ?? 0} />
              <StatChip label="Likes" value={stats?.likes ?? 0} />
              <StatChip label="Uploads (7 Tage)" value={stats?.recent_uploads ?? 0} />
            </CardContent>
          </Card>
        </div>
      ) : (
        <Alert variant="destructive">
          <AlertTitle>Event nicht gefunden</AlertTitle>
          <AlertDescription>Bitte prüfe den Slug und versuche es erneut.</AlertDescription>
        </Alert>
      )}
    </AdminLayout>
  );
}

function DetailSkeleton() {
  return (
    <div className="space-y-4">
      {Array.from({ length: 3 }).map((_, index) => (
        <div key={index} className="h-40 animate-pulse rounded-2xl bg-gradient-to-r from-white/40 via-white/60 to-white/40" />
      ))}
    </div>
  );
}

function InfoRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex flex-col gap-1 rounded-xl border border-pink-100 bg-white/70 px-3 py-2">
      <span className="text-xs uppercase tracking-wide text-slate-500">{label}</span>
      <span className="text-sm font-medium text-slate-800">{value}</span>
    </div>
  );
}

function StatChip({ label, value }: { label: string; value: string | number }) {
  return (
    <div className="rounded-2xl border border-sky-100 bg-white/80 px-4 py-3 text-center shadow-sm">
      <div className="text-xs uppercase tracking-wide text-slate-500">{label}</div>
      <div className="text-lg font-semibold text-slate-900">{value}</div>
    </div>
  );
}

function formatDate(iso: string | null): string {
  if (!iso) return 'Noch kein Datum';
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) {
    return 'Unbekanntes Datum';
  }
  return date.toLocaleDateString('de-DE', { day: '2-digit', month: 'long', year: 'numeric' });
}

function renderName(name: TenantEvent['name']): string {
  if (typeof name === 'string') {
    return name;
  }
  if (name && typeof name === 'object') {
    return name.de ?? name.en ?? Object.values(name)[0] ?? 'Unbenanntes Event';
  }
  return 'Unbenanntes Event';
}
