import React from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { CalendarDays, MapPin, Settings, Plus, Bell, ListTodo, Image as ImageIcon } 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, CTAButton, KpiTile, ActionTile } from './components/Primitives';
import { BottomNav } from './components/BottomNav';
import { getEvents, TenantEvent } from '../api';
import { adminPath } from '../constants';
import { isAuthError } from '../auth/tokens';
import { getApiErrorMessage } from '../lib/apiError';
import { useMobileNav } from './hooks/useMobileNav';
import { getEventStats, EventStats } from '../api';

export default function MobileDashboardPage() {
  const navigate = useNavigate();
  const { t } = useTranslation('management');
  const [events, setEvents] = React.useState<TenantEvent[]>([]);
  const [stats, setStats] = React.useState<Record<string, EventStats>>({});
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const { go } = useMobileNav();

  React.useEffect(() => {
    (async () => {
      try {
        setEvents(await getEvents());
        const fetched: Record<string, EventStats> = {};
        const list = await getEvents();
        await Promise.all(
          (list || []).map(async (ev) => {
            if (!ev.slug) return;
            try {
              fetched[ev.slug] = await getEventStats(ev.slug);
            } catch {
              // ignore per-event stat failures
            }
          })
        );
        setStats(fetched);
        setError(null);
      } catch (err) {
        if (!isAuthError(err)) {
          setError(getApiErrorMessage(err, t('events.errors.loadFailed', 'Events konnten nicht geladen werden.')));
        }
      } finally {
        setLoading(false);
      }
    })();
  }, [t]);

  return (
    <MobileScaffold
      title={t('events.list.dashboardTitle', 'All Events Dashboard')}
      onBack={() => navigate(-1)}
      rightSlot={
        <Pressable onPress={() => navigate(adminPath('/settings'))}>
          <Settings size={18} color="#0f172a" />
        </Pressable>
      }
      footer={
        <BottomNav active="events" onNavigate={go} />
      }
    >
      {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'))} />

      {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="$2">
          <Text fontSize="$md" fontWeight="700" color="#111827">
            {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('/mobile/events/new'))} />
        </MobileCard>
      ) : (
        <YStack space="$3">
          <MobileCard space="$3">
            <Text fontSize="$md" fontWeight="800" color="#111827">
              {t('dashboard.kpis', 'Key Performance Indicators')}
            </Text>
            <XStack space="$2" flexWrap="wrap">
              <KpiTile icon={ListTodo} label={t('events.detail.kpi.tasks', 'Tasks Completed')} value="—" />
              <KpiTile icon={Bell} label={t('events.detail.kpi.guests', 'Guests Registered')} value="—" />
              <KpiTile icon={ImageIcon} label={t('events.detail.kpi.photos', 'Images Uploaded')} value="—" />
            </XStack>
          </MobileCard>
          {events.map((event) => (
            <MobileCard key={event.id} borderColor="#e2e8f0" space="$2">
              <XStack justifyContent="space-between" alignItems="flex-start" space="$2">
                <YStack space="$1.5">
                  <Text fontSize="$lg" 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={resolveTone(event)}>{resolveStatus(event, t)}</PillBadge>
                </YStack>
                <Pressable onPress={() => navigate(adminPath(`/mobile/events/${event.slug}`))}>
                  <Text fontSize="$xl" color="#9ca3af">
                    ˅
                  </Text>
                </Pressable>
              </XStack>

              <XStack marginTop="$2" space="$2" flexWrap="wrap">
                <ActionTile
                  icon={ListTodo}
                  label={t('events.quick.tasks', 'Tasks')}
                  color="#60a5fa"
                  onPress={() => navigate(adminPath(`/mobile/events/${event.slug}/tasks`))}
                  width="32%"
                />
                <ActionTile
                  icon={ImageIcon}
                  label={t('events.quick.images', 'Images')}
                  color="#a855f7"
                  onPress={() => navigate(adminPath(`/mobile/events/${event.slug}/photos`))}
                  width="32%"
                />
                <ActionTile
                  icon={Bell}
                  label={t('alerts.title', 'Alerts')}
                  color="#fbbf24"
                  onPress={() => navigate(adminPath(`/mobile/alerts?event=${event.slug}`))}
                  width="32%"
                />
              </XStack>
            </MobileCard>
          ))}
        </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): 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 resolveStatus(event: TenantEvent, t: ReturnType<typeof useTranslation>['t']): string {
  if (event.status === 'published') return t('events.status.published', 'Upcoming');
  if (event.status === 'draft') return t('events.status.draft', 'Draft');
  return t('events.status.archived', 'Past');
}

function resolveTone(event: TenantEvent): 'success' | 'warning' | 'muted' {
  if (event.status === 'published') return 'success';
  if (event.status === 'draft') return 'warning';
  return 'muted';
}
