import React from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { AlertTriangle, ArrowRight, CalendarDays, Camera, Heart, Plus } from 'lucide-react';
import { YStack, XStack } from '@tamagui/stacks';
import { SizableText as Text } from '@tamagui/text';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { AppCard, PrimaryCTA, Segmented, StatusPill, MetaRow, BottomNav } from '../tamagui/primitives';

import { AdminLayout } from '../components/AdminLayout';
import { getEvents, TenantEvent } from '../api';
import { isAuthError } from '../auth/tokens';
import { getApiErrorMessage } from '../lib/apiError';
import {
  adminPath,
  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_PHOTOBOOTH_PATH,
  ADMIN_EVENT_BRANDING_PATH,
} from '../constants';
import { buildLimitWarnings } 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);
      }
    })();
  }, [t]);

  const translateManagement = React.useCallback(
    (key: string, fallback?: string, options?: Record<string, unknown>) =>
      t(key, { defaultValue: fallback, ...(options ?? {}) }),
    [t],
  );

  const translateCommon = React.useCallback(
    (key: string, fallback?: string, options?: Record<string, unknown>) =>
      tCommon(key, { defaultValue: fallback, ...(options ?? {}) }),
    [tCommon],
  );

  const totalEvents = rows.length;
  const publishedEvents = React.useMemo(
    () => rows.filter((event) => event.status === 'published').length,
    [rows],
  );

  const pageTitle = translateManagement('events.list.title', 'Deine Events');
  const draftEvents = totalEvents - publishedEvents;
  const [statusFilter, setStatusFilter] = React.useState<'all' | 'published' | 'draft'>('all');
  const filteredRows = React.useMemo(() => {
    if (statusFilter === 'published') {
      return rows.filter((event) => event.status === 'published');
    }
    if (statusFilter === 'draft') {
      return rows.filter((event) => event.status !== 'published');
    }
    return rows;
  }, [rows, statusFilter]);
  const filterOptions: Array<{ key: 'all' | 'published' | 'draft'; label: string; count: number }> = [
    { key: 'all', label: t('events.list.filters.all', 'Alle'), count: totalEvents },
    { key: 'published', label: t('events.list.filters.published', 'Live'), count: publishedEvents },
    { key: 'draft', label: t('events.list.filters.drafts', 'Entwürfe'), count: Math.max(0, draftEvents) },
  ];

  return (
    <AdminLayout title={pageTitle} disableCommandShelf>
      <YStack space="$3" maxWidth={560} marginHorizontal="auto" paddingBottom="$8">
        {error ? (
          <Alert variant="destructive">
            <AlertTitle>Fehler beim Laden</AlertTitle>
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        ) : null}

        <AppCard>
          <YStack space="$1">
            <Text fontSize="$lg" fontWeight="700" color="$color">
              {t('events.list.dashboardTitle', 'All Events Dashboard')}
            </Text>
            <Text fontSize="$sm" color="$color">
              {t('events.list.dashboardSubtitle', 'Schneller Überblick über deine Events')}
            </Text>
          </YStack>
          <Segmented
            options={filterOptions.map((opt) => ({ key: opt.key, label: `${opt.label} (${opt.count})` }))}
            value={statusFilter}
            onChange={(key) => setStatusFilter(key as typeof statusFilter)}
          />
          <PrimaryCTA label={t('events.actions.create', 'Create New Event')} onPress={() => navigate(adminPath('/events/new'))} />
        </AppCard>

        {loading ? (
          <LoadingState />
        ) : filteredRows.length === 0 ? (
          <EmptyState
            title={t('events.list.empty.title', 'Noch kein Event angelegt')}
            description={t(
              'events.list.empty.description',
              'Starte jetzt mit deinem ersten Event und lade Gäste in dein farbenfrohes Erlebnisportal ein.'
            )}
            onCreate={() => navigate(adminPath('/events/new'))}
          />
        ) : (
          <YStack space="$3">
            {filteredRows.map((event) => (
              <EventCard
                key={event.id}
                event={event}
                translate={translateManagement}
                translateCommon={translateCommon}
              />
            ))}
          </YStack>
        )}
      </YStack>
      <BottomNav
        active="events"
        onNavigate={(key) => {
          if (key === 'analytics') {
            navigate(adminPath('/dashboard'));
          } else if (key === 'settings') {
            navigate(adminPath('/settings'));
          } else {
            navigate(adminPath('/events'));
          }
        }}
      />
    </AdminLayout>
  );
}

function EventCard({
  event,
  translate,
  translateCommon,
}: {
  event: TenantEvent;
  translate: (key: string, fallback?: string, options?: Record<string, unknown>) => string;
  translateCommon: (key: string, fallback?: 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}`, undefined, opts)),
    [event.limits, translateCommon],
  );
  const statusLabel = translateCommon(
    event.status === 'published'
      ? 'events.status.published'
      : event.status === 'archived'
        ? 'events.status.archived'
        : 'events.status.draft',
    event.status === 'published' ? 'Live' : event.status === 'archived' ? 'Archiviert' : 'Entwurf',
  );
  const metaItems = [
    {
      key: 'date',
      label: translate('events.list.meta.date', 'Eventdatum'),
      value: formatDate(event.event_date),
      icon: <CalendarDays className="h-4 w-4 text-rose-500" />,
    },
    {
      key: 'photos',
      label: translate('events.list.meta.photos', 'Uploads'),
      value: photoCount,
      icon: <Camera className="h-4 w-4 text-fuchsia-500" />,
    },
    {
      key: 'likes',
      label: translate('events.list.meta.likes', 'Likes'),
      value: likeCount,
      icon: <Heart className="h-4 w-4 text-amber-500" />,
    },
  ];
  const secondaryLinks = [
    { key: 'edit', label: translateCommon('actions.edit', 'Bearbeiten'), to: ADMIN_EVENT_EDIT_PATH(slug) },
    { key: 'members', label: translate('events.list.actions.members', 'Mitglieder'), to: ADMIN_EVENT_MEMBERS_PATH(slug) },
    { key: 'tasks', label: translate('events.list.actions.tasks', 'Tasks'), to: ADMIN_EVENT_TASKS_PATH(slug) },
    { key: 'invites', label: translate('events.list.actions.invites', 'QR-Einladungen'), to: ADMIN_EVENT_INVITES_PATH(slug) },
    { key: 'branding', label: translate('events.list.actions.branding', 'Branding'), to: ADMIN_EVENT_BRANDING_PATH(slug) },
    { key: 'photobooth', label: translate('events.list.actions.photobooth', 'Photobooth'), to: ADMIN_EVENT_PHOTOBOOTH_PATH(slug) },
    { key: 'toolkit', label: translate('events.list.actions.toolkit', 'Toolkit'), to: ADMIN_EVENT_VIEW_PATH(slug) },
  ];

  return (
    <AppCard>
      <XStack justifyContent="space-between" alignItems="flex-start" space="$3">
        <YStack space="$1">
          <Text fontSize="$xs" letterSpacing={2.6} textTransform="uppercase" color="$color">
            {translate('events.list.item.label', 'Event')}
          </Text>
          <Text fontSize="$lg" fontWeight="700" color="$color">
            {renderName(event.name)}
          </Text>
          <MetaRow date={formatDate(event.event_date)} location={resolveLocation(event, translate)} status={statusLabel} />
        </YStack>
        <StatusPill tone={isPublished ? 'success' : 'warning'}>{statusLabel}</StatusPill>
      </XStack>

      <XStack space="$2" flexWrap="wrap">
        {metaItems.map((item) => (
          <MetaChip key={item.key} icon={item.icon} label={item.label} value={item.value} />
        ))}
      </XStack>

      {limitWarnings.length > 0 ? (
        <YStack space="$2">
          {limitWarnings.map((warning) => (
            <XStack
              key={warning.id}
              space="$2"
              alignItems="flex-start"
              borderWidth={1}
              borderRadius="$tile"
              padding="$3"
              backgroundColor={warning.tone === 'danger' ? '#fff1f2' : '#fffbeb'}
              borderColor={warning.tone === 'danger' ? '#fecdd3' : '#fef3c7'}
            >
              <AlertTriangle className="h-4 w-4" />
              <Text fontSize="$xs" color="$color">
                {warning.message}
              </Text>
            </XStack>
          ))}
        </YStack>
      ) : null}

      <XStack space="$2">
        <Link
          to={ADMIN_EVENT_VIEW_PATH(slug)}
          className="flex-1 rounded-xl bg-[#007AFF] px-4 py-3 text-center text-sm font-semibold text-white shadow-sm transition hover:opacity-90"
        >
          {translateCommon('actions.open', 'Öffnen')} <ArrowRight className="inline h-4 w-4" />
        </Link>
        <Link
          to={ADMIN_EVENT_PHOTOS_PATH(slug)}
          className="flex-1 rounded-xl border border-slate-200 px-4 py-3 text-center text-sm font-semibold text-[#007AFF] transition hover:bg-slate-50"
        >
          {translate('events.list.actions.photos', 'Fotos moderieren')}
        </Link>
      </XStack>

      <XStack flexWrap="wrap" space="$2">
        {secondaryLinks.map((action) => (
          <ActionChip key={action.key} to={action.to}>
            {action.label}
          </ActionChip>
        ))}
      </XStack>
    </AppCard>
  );
}

function MetaChip({
  icon,
  label,
  value,
}: {
  icon: React.ReactNode;
  label: string;
  value: string | number;
}) {
  return (
    <YStack borderWidth={1} borderColor="$muted" borderRadius="$tile" padding="$3" minWidth="45%">
      <XStack alignItems="center" space="$2">
        {icon}
        <Text fontSize="$xs" color="$color">
          {label}
        </Text>
      </XStack>
      <Text fontSize="$md" fontWeight="700" color="$color" marginTop="$1">
        {value}
      </Text>
    </YStack>
  );
}

function ActionChip({ to, children }: { to: string; children: React.ReactNode }) {
  return (
    <Link to={to} className="rounded-full border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-50">
      {children}
    </Link>
  );
}

function LoadingState() {
  return (
    <YStack space="$2">
      {Array.from({ length: 3 }).map((_, index) => (
        <AppCard key={index} height={96} opacity={0.6} />
      ))}
    </YStack>
  );
}

function EmptyState({
  title,
  description,
  onCreate,
}: {
  title: string;
  description: string;
  onCreate: () => void;
}) {
  return (
    <AppCard alignItems="center" justifyContent="center" space="$3" borderStyle="dashed" borderColor="$muted">
      <YStack bg="$muted" padding="$3" borderRadius="$pill">
        <Plus className="h-5 w-5 text-[#007AFF]" />
      </YStack>
      <YStack space="$1" alignItems="center">
        <Text fontSize="$lg" fontWeight="700" color="$color">
          {title}
        </Text>
        <Text fontSize="$sm" color="$color" textAlign="center">
          {description}
        </Text>
      </YStack>
      <PrimaryCTA label="Event erstellen" onPress={onCreate} />
    </AppCard>
  );
}

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';
}

function resolveLocation(
  event: TenantEvent,
  translate: (key: string, fallback?: string, options?: Record<string, unknown>) => string,
): string {
  const settings = (event.settings ?? {}) as Record<string, unknown>;
  const candidate =
    (settings.location as string | undefined) ??
    (settings.address as string | undefined) ??
    (settings.city as string | undefined);

  if (typeof candidate === 'string' && candidate.trim().length > 0) {
    return candidate;
  }

  return translate('events.list.meta.locationFallback', 'Ort folgt');
}
