import React from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { CalendarDays, MapPin, Settings, Users, Camera, Sparkles, QrCode, Image, Shield, Layout, RefreshCcw, ChevronDown } from 'lucide-react';
import { YStack, XStack } from '@tamagui/stacks';
import { SizableText as Text } from '@tamagui/text';
import { Pressable } from '@tamagui/react-native-web-lite';
import { MobileScaffold } from './components/Scaffold';
import { MobileCard, PillBadge, KpiTile, ActionTile } from './components/Primitives';
import { BottomNav } from './components/BottomNav';
import { TenantEvent, EventStats, EventToolkit, getEvent, getEventStats, getEventToolkit } from '../api';
import { adminPath, ADMIN_EVENT_BRANDING_PATH, ADMIN_EVENT_INVITES_PATH, ADMIN_EVENT_MEMBERS_PATH, ADMIN_EVENT_PHOTOS_PATH, ADMIN_EVENT_TASKS_PATH } from '../constants';
import { isAuthError } from '../auth/tokens';
import { getApiErrorMessage } from '../lib/apiError';
import { useMobileNav } from './hooks/useMobileNav';
import { MobileSheet } from './components/Sheet';
import { useEventContext } from '../context/EventContext';

export default function MobileEventDetailPage() {
  const { slug: slugParam } = useParams<{ slug?: string }>();
  const slug = slugParam ?? null;
  const navigate = useNavigate();
  const { t } = useTranslation('management');

  const [event, setEvent] = React.useState<TenantEvent | null>(null);
  const [stats, setStats] = React.useState<EventStats | null>(null);
  const [toolkit, setToolkit] = React.useState<EventToolkit | null>(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const { go } = useMobileNav(slug);
  const { events, activeEvent, selectEvent } = useEventContext();
  const [showEventPicker, setShowEventPicker] = React.useState(false);

  React.useEffect(() => {
    if (!slug) return;
    (async () => {
      setLoading(true);
      try {
        const [eventData, statsData, toolkitData] = await Promise.all([getEvent(slug), getEventStats(slug), getEventToolkit(slug)]);
        setEvent(eventData);
        setStats(statsData);
        setToolkit(toolkitData);
        setError(null);
      } catch (err) {
        if (!isAuthError(err)) {
          setError(getApiErrorMessage(err, t('events.errors.loadFailed', 'Event konnte nicht geladen werden.')));
        }
      } finally {
        setLoading(false);
      }
    })();
  }, [slug, t]);

  const kpis = [
    {
      label: t('events.detail.kpi.tasks', 'Tasks Completed'),
      value: toolkit?.tasks?.summary ? `${toolkit.tasks.summary.completed}/${toolkit.tasks.summary.total}` : '—',
      icon: Sparkles,
    },
    {
      label: t('events.detail.kpi.guests', 'Guests Registered'),
      value: toolkit?.invites?.summary.total ?? event?.active_invites_count ?? '—',
      icon: Users,
    },
    {
      label: t('events.detail.kpi.photos', 'Images Uploaded'),
      value: stats?.uploads_total ?? event?.photo_count ?? '—',
      icon: Camera,
    },
  ];

  return (
    <MobileScaffold
      title={t('events.detail.title', 'Event Details Dashboard')}
      onBack={() => navigate(adminPath('/mobile/events'))}
      rightSlot={
        <XStack space="$3" alignItems="center">
          <Pressable onPress={() => setShowEventPicker(true)}>
            <XStack alignItems="center" space="$1.5">
              <Text fontSize="$sm" color="#007AFF" fontWeight="600">
                {activeEvent?.name ?? t('events.detail.pickEvent', 'Event wählen')}
              </Text>
              <ChevronDown size={14} color="#007AFF" />
            </XStack>
          </Pressable>
          <Pressable onPress={() => navigate(adminPath('/settings'))}>
            <Settings size={18} color="#0f172a" />
          </Pressable>
          <Pressable onPress={() => navigate(0)}>
            <RefreshCcw size={18} color="#0f172a" />
          </Pressable>
        </XStack>
      }
      footer={
        <BottomNav active="home" onNavigate={go} />
      }
    >
      {error ? (
        <MobileCard>
          <Text fontWeight="700" color="#b91c1c">
            {error}
          </Text>
        </MobileCard>
      ) : null}

      <MobileCard space="$3">
        <Text fontSize="$lg" fontWeight="800" color="#111827">
          {event ? renderName(event.name) : t('events.placeholders.untitled', 'Unbenanntes Event')}
        </Text>
        <XStack alignItems="center" space="$2">
          <CalendarDays size={16} color="#6b7280" />
          <Text fontSize="$sm" color="#4b5563">
            {formatDate(event?.event_date)}
          </Text>
          <MapPin size={16} color="#6b7280" />
          <Text fontSize="$sm" color="#4b5563">
            {resolveLocation(event)}
          </Text>
        </XStack>
        <PillBadge tone={event?.status === 'published' ? 'success' : 'warning'}>
          {event?.status === 'published' ? t('events.status.published', 'Live') : t('events.status.draft', 'Draft')}
        </PillBadge>
      </MobileCard>

      <YStack space="$2">
        {loading ? (
          <XStack space="$2" flexWrap="wrap">
            {Array.from({ length: 3 }).map((_, idx) => (
              <MobileCard key={`kpi-${idx}`} height={90} width="32%" />
            ))}
          </XStack>
        ) : (
          <XStack space="$2" flexWrap="wrap">
            {kpis.map((kpi) => (
              <KpiTile key={kpi.label} icon={kpi.icon} label={kpi.label} value={kpi.value} />
            ))}
          </XStack>
        )}
      </YStack>

      <MobileSheet
        open={showEventPicker}
        onClose={() => setShowEventPicker(false)}
        title={t('events.detail.pickEvent', 'Event wählen')}
        footer={null}
        bottomOffsetPx={120}
      >
        <YStack space="$2">
          {events.length === 0 ? (
            <Text fontSize={12.5} color="#4b5563">
              {t('events.list.empty.description', 'Starte jetzt mit deinem ersten Event.')}
            </Text>
          ) : (
            events.map((ev) => (
              <Pressable
                key={ev.slug}
                onPress={() => {
                  selectEvent(ev.slug ?? null);
                  setShowEventPicker(false);
                  navigate(adminPath(`/mobile/events/${ev.slug}`));
                }}
              >
                <XStack alignItems="center" justifyContent="space-between" paddingVertical="$2">
                  <YStack space="$1">
                    <Text fontSize={13} fontWeight="700" color="#111827">
                      {renderName(ev.name)}
                    </Text>
                    <XStack alignItems="center" space="$1.5">
                      <CalendarDays size={14} color="#6b7280" />
                      <Text fontSize={12} color="#4b5563">
                        {formatDate(ev.event_date)}
                      </Text>
                    </XStack>
                  </YStack>
                  <PillBadge tone={ev.slug === activeEvent?.slug ? 'success' : 'muted'}>
                    {ev.slug === activeEvent?.slug ? t('events.detail.active', 'Aktiv') : t('events.actions.open', 'Öffnen')}
                  </PillBadge>
                </XStack>
              </Pressable>
            ))
          )}
        </YStack>
      </MobileSheet>

      <YStack space="$2">
        <Text fontSize="$md" fontWeight="800" color="#111827">
          {t('events.detail.managementTitle', 'Event Management')}
        </Text>
        <XStack flexWrap="wrap" space="$2">
          <ActionTile
            icon={Sparkles}
            label={t('events.quick.tasks', 'Tasks & Checklists')}
            color="#60a5fa"
            onPress={() => navigate(adminPath(`/mobile/events/${slug ?? ''}/tasks`))}
          />
          <ActionTile
            icon={QrCode}
            label={t('events.quick.qr', 'QR Code Layouts')}
            color="#fbbf24"
            onPress={() => navigate(adminPath(`/mobile/events/${slug ?? ''}/qr`))}
          />
          <ActionTile
            icon={Image}
            label={t('events.quick.images', 'Image Management')}
            color="#a855f7"
            onPress={() => navigate(adminPath(`/mobile/events/${slug ?? ''}/photos`))}
          />
          <ActionTile
            icon={Users}
            label={t('events.quick.guests', 'Guest Management')}
            color="#4ade80"
            onPress={() => navigate(adminPath(`/mobile/events/${slug ?? ''}/members`))}
          />
          <ActionTile
            icon={Layout}
            label={t('events.quick.branding', 'Branding & Theme')}
            color="#fb7185"
            onPress={() => navigate(adminPath(`/mobile/events/${slug ?? ''}/branding`))}
          />
          <ActionTile
            icon={Shield}
            label={t('events.quick.moderation', 'Photo Moderation')}
            color="#38bdf8"
            onPress={() => navigate(adminPath(`/mobile/events/${slug ?? ''}/photos`))}
          />
        </XStack>
      </YStack>
    </MobileScaffold>
  );
}

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 formatDate(iso?: string | null): string {
  if (!iso) return 'Date tbd';
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return 'Date tbd';
  return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
}

function resolveLocation(event: TenantEvent | null): string {
  if (!event) return 'Location';
  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 (candidate && candidate.trim()) {
    return candidate;
  }
  return 'Location';
}
