import React from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { AlertTriangle, ArrowRight, CalendarDays, Plus, Settings, Sparkles, Share2 } from 'lucide-react';

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

import { AdminLayout } from '../components/AdminLayout';
import { getEvents, TenantEvent } from '../api';
import { isAuthError } from '../auth/tokens';
import { getApiErrorMessage } from '../lib/apiError';
import {
  adminPath,
  ADMIN_SETTINGS_PATH,
  ADMIN_EVENT_VIEW_PATH,
  ADMIN_EVENT_EDIT_PATH,
  ADMIN_EVENT_PHOTOS_PATH,
  ADMIN_EVENT_MEMBERS_PATH,
  ADMIN_EVENT_TASKS_PATH,
  ADMIN_EVENT_INVITES_PATH,
  ADMIN_EVENT_TOOLKIT_PATH,
} from '../constants';
import { buildLimitWarnings, type EventLimitSummary } from '../lib/limitWarnings';
import { useTranslation } from 'react-i18next';

export default function EventsPage() {
  const { t } = useTranslation('management');
  const { t: tCommon } = useTranslation('common');
  const [rows, setRows] = React.useState<TenantEvent[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const navigate = useNavigate();

  React.useEffect(() => {
    (async () => {
      try {
        setRows(await getEvents());
      } catch (err) {
        if (!isAuthError(err)) {
          setError(getApiErrorMessage(err, t('events.errors.loadFailed', 'Event konnte nicht geladen werden.')));
        }
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  const actions = (
    <>
      <Button
        className="bg-gradient-to-r from-pink-500 via-fuchsia-500 to-purple-500 text-white shadow-lg shadow-pink-500/20"
        onClick={() => navigate(adminPath('/events/new'))}
      >
        <Plus className="h-4 w-4" /> {t('events.list.actions.create', 'Neues Event')}
      </Button>
      <Link to={ADMIN_SETTINGS_PATH}>
        <Button variant="outline" className="border-pink-200 text-pink-600 hover:bg-pink-50">
          <Settings className="h-4 w-4" /> {t('events.list.actions.settings', 'Einstellungen')}
        </Button>
      </Link>
    </>
  );

  return (
    <AdminLayout
      title={t('events.list.title', 'Deine Events')}
      subtitle={t('events.list.subtitle', 'Plane Momente, die in Erinnerung bleiben. Hier verwaltest du alles rund um deine Veranstaltungen.')}
      actions={actions}
    >
      {error && (
        <Alert variant="destructive">
          <AlertTitle>Fehler beim Laden</AlertTitle>
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      <Card className="border-0 bg-white/80 shadow-xl shadow-pink-100/60">
        <CardHeader className="flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between">
          <div>
          <CardTitle className="text-xl font-semibold text-slate-900">{t('events.list.overview.title', 'Übersicht')}</CardTitle>
            <CardDescription className="text-slate-600">
              {rows.length === 0
                ? t('events.list.overview.empty', 'Noch keine Events - starte jetzt und lege dein erstes Event an.')
                : t('events.list.overview.count', '{{count}} Events aktiv verwaltet.', { count: rows.length })}
            </CardDescription>
          </div>
          <div className="flex items-center gap-2 text-sm text-pink-600">
            <Sparkles className="h-4 w-4" /> {t('events.list.badge.dashboard', 'Tenant Dashboard')}
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {loading ? (
            <LoadingState />
          ) : rows.length === 0 ? (
            <EmptyState onCreate={() => navigate(adminPath('/events/new'))} />
          ) : (
            <div className="space-y-4">
              {rows.map((event) => (
                <EventCard key={event.id} event={event} translateCommon={tCommon} />
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </AdminLayout>
  );
}

function EventCard({
  event,
  translateCommon,
}: {
  event: TenantEvent;
  translateCommon: (key: string, options?: Record<string, unknown>) => string;
}) {
  const slug = event.slug;
  const isPublished = event.status === 'published';
  const photoCount = event.photo_count ?? 0;
  const likeCount = event.like_count ?? 0;
  const limitWarnings = React.useMemo(
    () => buildLimitWarnings(event.limits ?? null, (key, opts) => translateCommon(`limits.${key}`, opts)),
    [event.limits, translateCommon],
  );

  return (
    <div className="rounded-2xl border border-white/80 bg-white/90 p-5 shadow-md shadow-pink-200/40 transition-transform hover:-translate-y-0.5 hover:shadow-lg">
      {limitWarnings.length > 0 && (
        <div className="mb-3 space-y-1">
          {limitWarnings.map((warning) => (
            <Alert
              key={warning.id}
              variant={warning.tone === 'danger' ? 'destructive' : 'default'}
              className={warning.tone === 'warning' ? 'border-amber-400/40 bg-amber-50 text-amber-900' : undefined}
            >
              <AlertDescription className="flex items-center gap-2 text-xs">
                <AlertTriangle className="h-4 w-4" />
                {warning.message}
              </AlertDescription>
            </Alert>
          ))}
        </div>
      )}

      <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
        <div className="space-y-1">
          <h3 className="text-lg font-semibold text-slate-900">{renderName(event.name)}</h3>
          <div className="flex flex-wrap items-center gap-2 text-xs text-slate-600">
            <span className="inline-flex items-center gap-1 rounded-full bg-pink-100 px-3 py-1 font-medium text-pink-700">
              <CalendarDays className="h-3.5 w-3.5" />
              {formatDate(event.event_date)}
            </span>
            <span className="inline-flex items-center gap-1 rounded-full bg-sky-100 px-3 py-1 font-medium text-sky-700">
              Photos: {photoCount}
            </span>
            <span className="inline-flex items-center gap-1 rounded-full bg-amber-100 px-3 py-1 font-medium text-amber-700">
              Likes: {likeCount}
            </span>
          </div>
        </div>
        <Badge
          className={
            isPublished
              ? 'bg-emerald-500/90 text-white shadow shadow-emerald-500/30'
              : 'bg-slate-200 text-slate-700'
          }
        >
          {isPublished ? 'Veroeffentlicht' : 'Entwurf'}
        </Badge>
      </div>

      <div className="mt-4 flex flex-wrap gap-2">
        <Button asChild variant="outline" className="border-pink-200 text-pink-700 hover:bg-pink-50">
          <Link to={ADMIN_EVENT_VIEW_PATH(slug)}>
            Details <ArrowRight className="ml-1 h-3.5 w-3.5" />
          </Link>
        </Button>
        <Button asChild variant="outline" className="border-fuchsia-200 text-fuchsia-700 hover:bg-fuchsia-50">
          <Link to={ADMIN_EVENT_EDIT_PATH(slug)}>Bearbeiten</Link>
        </Button>
        <Button asChild variant="outline" className="border-sky-200 text-sky-700 hover:bg-sky-50">
          <Link to={ADMIN_EVENT_PHOTOS_PATH(slug)}>Fotos moderieren</Link>
        </Button>
        <Button asChild variant="outline" className="border-emerald-200 text-emerald-600 hover:bg-emerald-50">
          <Link to={ADMIN_EVENT_MEMBERS_PATH(slug)}>Mitglieder</Link>
        </Button>
        <Button asChild variant="outline" className="border-amber-200 text-amber-600 hover:bg-amber-50">
          <Link to={ADMIN_EVENT_TASKS_PATH(slug)}>Tasks</Link>
        </Button>
        <Button asChild variant="outline" className="border-slate-200 text-slate-700 hover:bg-slate-50">
          <Link to={ADMIN_EVENT_INVITES_PATH(slug)}>
            <Share2 className="h-3.5 w-3.5" /> QR-Einladungen
          </Link>
        </Button>
        <Button asChild variant="outline" className="border-emerald-200 text-emerald-600 hover:bg-emerald-50">
          <Link to={ADMIN_EVENT_TOOLKIT_PATH(slug)}>Toolkit</Link>
        </Button>
      </div>
    </div>
  );
}

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

function EmptyState({ onCreate }: { onCreate: () => void }) {
  return (
    <div className="flex flex-col items-center justify-center gap-3 rounded-2xl border border-dashed border-pink-200 bg-white/70 p-10 text-center">
      <div className="rounded-full bg-pink-100 p-3 text-pink-600 shadow-inner shadow-pink-200/80">
        <Plus className="h-5 w-5" />
      </div>
      <div className="space-y-1">
        <h3 className="text-lg font-semibold text-slate-900">Noch kein Event angelegt</h3>
        <p className="text-sm text-slate-600">
          Starte jetzt mit deinem ersten Event und lade Gäste in dein farbenfrohes Erlebnisportal ein.
        </p>
      </div>
      <Button
        onClick={onCreate}
        className="bg-gradient-to-r from-pink-500 via-fuchsia-500 to-purple-500 text-white shadow-lg shadow-pink-500/20"
      >
        <Plus className="mr-1 h-4 w-4" /> Event erstellen
      </Button>
    </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: 'short',
    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';
}
