import React from 'react';
import { useNavigate } from 'react-router-dom';
import { CalendarDays, MapPin, Plus, Search } 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 { useTranslation } from 'react-i18next';
import { MobileShell } from './components/MobileShell';
import { MobileCard, PillBadge, CTAButton } from './components/Primitives';
import { getEvents, TenantEvent } from '../api';
import { adminPath } from '../constants';
import { isAuthError } from '../auth/tokens';
import { getApiErrorMessage } from '../lib/apiError';

export default function MobileEventsPage() {
  const { t } = useTranslation('management');
  const navigate = useNavigate();
  const [events, setEvents] = React.useState<TenantEvent[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const [query, setQuery] = React.useState('');

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

  return (
    <MobileShell
      activeTab="home"
      title={t('events.list.dashboardTitle', 'All Events Dashboard')}
      onBack={() => navigate(-1)}
      headerActions={
        <Pressable>
          <Search size={18} color="#0f172a" />
        </Pressable>
      }
    >
      {error ? (
        <MobileCard>
          <Text fontWeight="700" color="#b91c1c">
            {error}
          </Text>
        </MobileCard>
      ) : null}

      <CTAButton label={t('events.actions.create', 'Create New Event')} onPress={() => navigate(adminPath('/mobile/events/new'))} />

      <input
        type="search"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder={t('events.list.search', 'Search events')}
        style={{
          width: '100%',
          height: 38,
          borderRadius: 10,
          border: '1px solid #e5e7eb',
          padding: '0 12px',
          fontSize: 13,
          background: 'white',
          marginBottom: 12,
        }}
      />

      {loading ? (
        <YStack space="$2">
          {Array.from({ length: 3 }).map((_, idx) => (
            <MobileCard key={`sk-${idx}`} height={90} opacity={0.6} />
          ))}
        </YStack>
      ) : events.length === 0 ? (
        <MobileCard alignItems="center" justifyContent="center" space="$3">
          <Text fontSize="$md" fontWeight="700">
            {t('events.list.empty.title', 'Noch kein Event angelegt')}
          </Text>
          <Text fontSize="$sm" color="#4b5563" textAlign="center">
            {t('events.list.empty.description', 'Starte jetzt mit deinem ersten Event.')}
          </Text>
          <CTAButton label={t('events.actions.create', 'Create New Event')} onPress={() => navigate(adminPath('/events/new'))} />
        </MobileCard>
      ) : (
        <YStack space="$3">
          {events
            .filter((event) => {
              if (!query.trim()) return true;
              const hay = `${event.name ?? ''} ${event.location ?? ''}`.toLowerCase();
              return hay.includes(query.toLowerCase());
            })
            .map((event) => (
              <EventRow
                key={event.id}
                event={event}
                onOpen={(slug) => navigate(adminPath(`/mobile/events/${slug}`))}
                onEdit={(slug) => navigate(adminPath(`/mobile/events/${slug}/edit`))}
              />
            ))}
        </YStack>
      )}
    </MobileShell>
  );
}

function EventRow({ event, onOpen, onEdit }: { event: TenantEvent; onOpen: (slug: string) => void; onEdit: (slug: string) => void }) {
  const status = resolveStatus(event);
  return (
    <MobileCard borderColor="#e2e8f0">
      <XStack justifyContent="space-between" alignItems="flex-start" space="$2">
        <YStack space="$1">
          <Text fontSize="$md" fontWeight="800" color="#111827">
            {renderName(event.name)}
          </Text>
          <XStack alignItems="center" space="$2">
            <CalendarDays size={14} color="#6b7280" />
            <Text fontSize="$sm" color="#4b5563">
              {formatDate(event.event_date)}
            </Text>
          </XStack>
          <XStack alignItems="center" space="$2">
            <MapPin size={14} color="#6b7280" />
            <Text fontSize="$sm" color="#4b5563">
              {resolveLocation(event)}
            </Text>
          </XStack>
          <PillBadge tone={status.tone}>{status.label}</PillBadge>
        </YStack>
        <Pressable onPress={() => onEdit(event.slug)}>
          <Text fontSize="$xl" color="#9ca3af">
            ˅
          </Text>
        </Pressable>
      </XStack>

      <Pressable onPress={() => onOpen(event.slug)} style={{ marginTop: 8 }}>
        <XStack alignItems="center" justifyContent="flex-start" space="$2">
          <Plus size={16} color="#007AFF" />
          <Text fontSize="$sm" color="#007AFF" fontWeight="700">
            Open event
          </Text>
        </XStack>
      </Pressable>
    </MobileCard>
  );
}

function resolveStatus(event: TenantEvent): { label: string; tone: 'success' | 'warning' | 'muted' } {
  if (event.status === 'published') {
    return { label: 'Upcoming', tone: 'success' };
  }
  if (event.status === 'draft') {
    return { label: 'Draft', tone: 'warning' };
  }
  return { label: 'Past', tone: 'muted' };
}

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): 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 (candidate && candidate.trim()) {
    return candidate;
  }
  return 'Location';
}

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