import React from 'react';
import { useNavigate } from 'react-router-dom';
import { CalendarDays, MapPin, Plus, Search, Camera, Users, Sparkles, ChevronRight } from 'lucide-react';
import { Card } from '@tamagui/card';
import { YStack, XStack } from '@tamagui/stacks';
import { SizableText as Text } from '@tamagui/text';
import { Pressable } from '@tamagui/react-native-web-lite';
import { ScrollView } from '@tamagui/scroll-view';
import { ToggleGroup } from '@tamagui/toggle-group';
import { ListItem } from '@tamagui/list-item';
import { YGroup } from '@tamagui/group';
import { useTranslation } from 'react-i18next';
import { MobileShell, HeaderActionButton } from './components/MobileShell';
import { PillBadge, CTAButton, FloatingActionButton, SkeletonCard } from './components/Primitives';
import { MobileInput } from './components/FormControls';
import { getEvents, getTenantPackagesOverview, TenantEvent, type TenantPackageSummary } from '../api';
import { adminPath } from '../constants';
import { isAuthError } from '../auth/tokens';
import { getApiErrorMessage } from '../lib/apiError';
import { useBackNavigation } from './hooks/useBackNavigation';
import { buildEventStatusCounts, filterEventsByStatus, resolveEventStatusKey, type EventStatusKey } from './lib/eventFilters';
import { buildEventListStats } from './lib/eventListStats';
import { useAdminTheme } from './theme';
import { useAuth } from '../auth/context';

export default function MobileEventsPage() {
  const { t } = useTranslation('management');
  const navigate = useNavigate();
  const { user } = useAuth();
  const isMember = user?.role === 'member';
  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('');
  const [statusFilter, setStatusFilter] = React.useState<EventStatusKey>('all');
  const [packagesOverview, setPackagesOverview] = React.useState<{
    packages: TenantPackageSummary[];
    activePackage: TenantPackageSummary | null;
  } | null>(null);
  const [packagesLoading, setPackagesLoading] = React.useState(false);
  const searchRef = React.useRef<HTMLInputElement>(null);
  const back = useBackNavigation();
  const { text, muted, subtle, border, primary, danger, surface, surfaceMuted, accentSoft, accent, shadow } = useAdminTheme();
  React.useEffect(() => {
    (async () => {
      try {
        setEvents(await getEvents());
      } catch (err) {
        if (!isAuthError(err)) {
          setError(getApiErrorMessage(err, t('events.errors.loadFailed')));
        }
      } finally {
        setLoading(false);
      }
    })();
  }, [t]);

  React.useEffect(() => {
    if (isMember) {
      return;
    }

    let isActive = true;
    setPackagesLoading(true);
    getTenantPackagesOverview()
      .then((overview) => {
        if (isActive) {
          setPackagesOverview(overview);
        }
      })
      .catch(() => {
        if (isActive) {
          setPackagesOverview(null);
        }
      })
      .finally(() => {
        if (isActive) {
          setPackagesLoading(false);
        }
      });

    return () => {
      isActive = false;
    };
  }, [isMember]);

  const canCreateEvent = React.useMemo(() => {
    if (isMember || packagesLoading) {
      return false;
    }

    const activePackages = collectActivePackages(packagesOverview);
    return activePackages.some((pkg) => packageHasRemainingEvents(pkg));
  }, [isMember, packagesLoading, packagesOverview]);

  return (
    <MobileShell
      activeTab="home"
      title={t('events.list.title')}
      onBack={back}
      headerActions={
        <HeaderActionButton
          onPress={() => searchRef.current?.focus()}
          ariaLabel={t('events.detail.pickEvent')}
        >
          <Search size={18} color={text} />
        </HeaderActionButton>
      }
    >
      {error ? (
        <Card
          borderRadius={22}
          borderWidth={2}
          borderColor={border}
          backgroundColor={surface}
          padding="$3"
          shadowColor={shadow}
          shadowOpacity={0.16}
          shadowRadius={16}
          shadowOffset={{ width: 0, height: 10 }}
        >
          <Text fontWeight="700" color={danger}>
            {error}
          </Text>
        </Card>
      ) : null}

      <Card
        borderRadius={22}
        borderWidth={2}
        borderColor={border}
        backgroundColor={surface}
        padding="$3"
        shadowColor={shadow}
        shadowOpacity={0.16}
        shadowRadius={16}
        shadowOffset={{ width: 0, height: 10 }}
      >
        <YStack space="$2.5">
          <XStack
            alignItems="center"
            paddingHorizontal="$3"
            paddingVertical="$1.5"
            borderRadius={999}
            borderWidth={1}
            borderColor={border}
            backgroundColor={surfaceMuted}
          >
            <Text fontSize="$xs" fontWeight="800" color={text}>
              {t('events.list.overview.title')}
            </Text>
          </XStack>
          <MobileInput
            ref={searchRef}
            type="search"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder={t('events.detail.pickEvent')}
            compact
          />
          <Text fontSize="$xs" color={muted}>
            {t('events.list.subtitle')}
          </Text>
        </YStack>
      </Card>

      {loading ? (
        <YStack space="$2">
          {Array.from({ length: 3 }).map((_, idx) => (
            <SkeletonCard key={`sk-${idx}`} height={90} />
          ))}
        </YStack>
      ) : events.length === 0 ? (
        <Card
          borderRadius={22}
          borderWidth={2}
          borderColor={border}
          backgroundColor={surface}
          padding="$3"
          shadowColor={shadow}
          shadowOpacity={0.16}
          shadowRadius={16}
          shadowOffset={{ width: 0, height: 10 }}
        >
          <YStack space="$2" alignItems="center">
            <Text fontSize="$md" fontWeight="700">
              {t('events.list.title')}
            </Text>
            <Text fontSize="$sm" color={muted} textAlign="center">
              {t('events.list.overview.empty')}
            </Text>
            {!isMember ? (
              <CTAButton
                label={t('events.list.actions.create')}
                onPress={() => navigate(adminPath('/events/new'))}
              />
            ) : null}
          </YStack>
        </Card>
      ) : (
        <EventsList
          events={events}
          query={query}
          statusFilter={statusFilter}
          onStatusChange={setStatusFilter}
          onOpen={(slug) => navigate(adminPath(`/mobile/events/${slug}`))}
          onEdit={!isMember ? (slug) => navigate(adminPath(`/mobile/events/${slug}/edit`)) : undefined}
        />
      )}

      {canCreateEvent ? (
        <FloatingActionButton
          label={t('events.list.actions.create')}
          icon={Plus}
          onPress={() => navigate(adminPath('/mobile/events/new'))}
        />
      ) : null}
    </MobileShell>
  );
}

function EventsList({
  events,
  query,
  statusFilter,
  onStatusChange,
  onOpen,
  onEdit,
}: {
  events: TenantEvent[];
  query: string;
  statusFilter: EventStatusKey;
  onStatusChange: (value: EventStatusKey) => void;
  onOpen: (slug: string) => void;
  onEdit?: (slug: string) => void;
}) {
  const { t } = useTranslation('management');
  const { text, muted, subtle, border, primary, surface, surfaceMuted, accentSoft, accent, shadow } = useAdminTheme();
  const activeBg = accentSoft;
  const activeBorder = accent;

  const statusCounts = React.useMemo(() => buildEventStatusCounts(events), [events]);
  const filteredByStatus = React.useMemo(
    () => filterEventsByStatus(events, statusFilter),
    [events, statusFilter]
  );
  const filteredEvents = React.useMemo(() => {
    if (!query.trim()) return filteredByStatus;
    const needle = query.toLowerCase();
    return filteredByStatus.filter((event) => {
      const name = resolveEventSearchName(event.name, t);
      const location = resolveLocation(event, t);
      const hay = `${name} ${location}`.toLowerCase();
      return hay.includes(needle);
    });
  }, [filteredByStatus, query, t]);

  const filters: Array<{ key: EventStatusKey; label: string; count: number }> = [
    { key: 'all', label: t('events.list.filters.all'), count: statusCounts.all },
    { key: 'upcoming', label: t('events.list.filters.upcoming'), count: statusCounts.upcoming },
    { key: 'draft', label: t('events.list.filters.draft'), count: statusCounts.draft },
    { key: 'past', label: t('events.list.filters.past'), count: statusCounts.past },
  ];

  return (
    <YStack space="$3">
      {filteredEvents.length === 0 ? (
        <Card
          borderRadius={22}
          borderWidth={2}
          borderColor={border}
          backgroundColor={surface}
          padding="$3"
          shadowColor={shadow}
          shadowOpacity={0.14}
          shadowRadius={14}
          shadowOffset={{ width: 0, height: 8 }}
        >
          <YStack space="$2" alignItems="center">
            <Text fontSize="$sm" fontWeight="700" color={text}>
              {t('events.list.empty.filtered')}
            </Text>
            <Text fontSize="$xs" color={muted} textAlign="center">
              {t('events.list.empty.filteredHint')}
            </Text>
            <CTAButton
              label={t('events.list.filters.all')}
              tone="ghost"
              fullWidth={false}
              onPress={() => onStatusChange('all')}
            />
          </YStack>
        </Card>
      ) : (
        <Card
          borderRadius={22}
          borderWidth={2}
          borderColor={border}
          backgroundColor={surface}
          padding="$2.5"
          shadowColor={shadow}
          shadowOpacity={0.14}
          shadowRadius={14}
          shadowOffset={{ width: 0, height: 8 }}
        >
          <YStack space="$2.5">
            <XStack alignItems="center" justifyContent="space-between">
              <Text fontSize="$xs" fontWeight="800" color={text}>
                {t('events.workspace.fields.status')}
              </Text>
              <Text fontSize="$xs" color={muted}>
                {t('events.list.subtitle')}
              </Text>
            </XStack>
            <ScrollView horizontal showsHorizontalScrollIndicator={false}>
              <XStack
                alignItems="center"
                padding="$1"
                borderRadius={999}
                borderWidth={1}
                borderColor={border}
                backgroundColor={surfaceMuted}
              >
                <ToggleGroup
                  type="single"
                  value={statusFilter}
                  onValueChange={(value) => value && onStatusChange(value as EventStatusKey)}
                >
                  <XStack space="$1.5">
                    {filters.map((filter) => {
                      const active = filter.key === statusFilter;
                      return (
                        <ToggleGroup.Item
                          key={filter.key}
                          value={filter.key}
                          borderRadius={999}
                          borderWidth={1}
                          borderColor={active ? activeBorder : 'transparent'}
                          backgroundColor={active ? activeBg : 'transparent'}
                          paddingVertical="$1.5"
                          paddingHorizontal="$3"
                        >
                          <XStack alignItems="center" space="$1.5">
                            <Text fontSize="$xs" fontWeight="700" color={active ? primary : muted}>
                              {filter.label}
                            </Text>
                            <XStack
                              paddingHorizontal="$1.5"
                              paddingVertical="$0.5"
                              borderRadius={999}
                              borderWidth={1}
                              borderColor={active ? activeBorder : border}
                              backgroundColor={surface}
                            >
                              <Text fontSize={10} fontWeight="800" color={active ? primary : muted}>
                                {filter.count}
                              </Text>
                            </XStack>
                          </XStack>
                        </ToggleGroup.Item>
                      );
                    })}
                  </XStack>
                </ToggleGroup>
              </XStack>
            </ScrollView>
          </YStack>

          <YGroup
            {...({
              borderRadius: 18,
              borderWidth: 1,
              borderColor: border,
              overflow: 'hidden',
              backgroundColor: surface,
            } as any)}
            marginTop="$2.5"
          >
            {filteredEvents.map((event) => {
              const statusKey = resolveEventStatusKey(event);
              const statusLabel =
                statusKey === 'draft'
                  ? t('events.list.filters.draft')
                  : statusKey === 'past'
                    ? t('events.list.filters.past')
                    : t('events.list.filters.upcoming');
              const statusTone = statusKey === 'draft' ? 'warning' : statusKey === 'past' ? 'muted' : 'success';
              return (
                <YGroup.Item key={event.id}>
                  <ListItem
                    hoverTheme
                    pressTheme
                    paddingVertical="$3"
                    paddingHorizontal="$3"
                    backgroundColor={surface}
                    onPress={() => onOpen(event.slug)}
                    title={
                      <EventListItem
                        event={event}
                        text={text}
                        muted={muted}
                        subtle={subtle}
                        primary={primary}
                        statusLabel={statusLabel}
                        statusTone={statusTone}
                        onEdit={onEdit}
                      />
                    }
                    iconAfter={
                      <XStack alignItems="center" space="$1.5">
                        <Text fontSize="$xs" color={primary} fontWeight="700">
                          {t('events.list.actions.open')}
                        </Text>
                        <ChevronRight size={16} color={primary} />
                      </XStack>
                    }
                  />
                </YGroup.Item>
              );
            })}
          </YGroup>
        </Card>
      )}
    </YStack>
  );
}

function EventListItem({
  event,
  text,
  muted,
  subtle,
  primary,
  statusLabel,
  statusTone,
  onEdit,
}: {
  event: TenantEvent;
  text: string;
  muted: string;
  subtle: string;
  primary: string;
  statusLabel: string;
  statusTone: 'success' | 'warning' | 'muted';
  onEdit?: (slug: string) => void;
}) {
  const { t, i18n } = useTranslation('management');
  const locale = i18n.language;
  const stats = buildEventListStats(event);
  return (
    <YStack space="$1.5">
      <XStack alignItems="center" justifyContent="space-between" space="$2">
        <Text fontSize="$md" fontWeight="800" color={text}>
          {renderName(event.name, t)}
        </Text>
        <XStack alignItems="center" space="$1.5">
          <PillBadge tone={statusTone}>{statusLabel}</PillBadge>
          {onEdit ? (
            <Pressable onPress={() => onEdit(event.slug)}>
              <Text fontSize="$xs" color={primary} fontWeight="700">
                {t('events.list.actions.settings', 'Settings')}
              </Text>
            </Pressable>
          ) : null}
        </XStack>
      </XStack>
      <XStack alignItems="center" space="$2" flexWrap="wrap">
        <XStack alignItems="center" space="$1.5">
          <CalendarDays size={12} color={subtle} />
          <Text fontSize="$xs" color={muted}>
            {formatDate(event.event_date, t, locale)}
          </Text>
        </XStack>
        <XStack alignItems="center" space="$1.5">
          <MapPin size={12} color={subtle} />
          <Text fontSize="$xs" color={muted}>
            {resolveLocation(event, t)}
          </Text>
        </XStack>
      </XStack>
      <XStack alignItems="center" space="$2" flexWrap="wrap">
        <EventStatChip icon={Camera} label={t('events.list.stats.photos')} value={stats.photos} muted={subtle} />
        <EventStatChip icon={Users} label={t('events.list.stats.guests')} value={stats.guests} muted={subtle} />
        <EventStatChip icon={Sparkles} label={t('events.list.stats.tasks')} value={stats.tasks} muted={subtle} />
      </XStack>
    </YStack>
  );
}

function EventStatChip({
  icon: Icon,
  label,
  value,
  muted,
}: {
  icon: typeof Camera;
  label: string;
  value: number;
  muted: string;
}) {
  return (
    <XStack alignItems="center" space="$1">
      <Icon size={12} color={muted} />
      <Text fontSize="$xs" color={muted}>
        {value} {label}
      </Text>
    </XStack>
  );
}

function renderName(name: TenantEvent['name'], t: (key: string) => string): string {
  if (typeof name === 'string') return name;
  if (name && typeof name === 'object') {
    return name.de ?? name.en ?? Object.values(name)[0] ?? t('events.placeholders.untitled');
  }
  return t('events.placeholders.untitled');
}

function collectActivePackages(
  overview: { packages: TenantPackageSummary[]; activePackage: TenantPackageSummary | null } | null
): TenantPackageSummary[] {
  if (!overview) {
    return [];
  }

  const packages = overview.packages ?? [];
  const activePackage = overview.activePackage;
  const activeList = packages.filter((pkg) => pkg.active);

  if (activePackage && !activeList.some((pkg) => pkg.id === activePackage.id) && activePackage.active) {
    return [activePackage, ...activeList];
  }

  return activeList;
}

function toNumber(value: unknown): number | null {
  if (typeof value === 'number' && Number.isFinite(value)) {
    return value;
  }

  if (typeof value === 'string' && value.trim() !== '') {
    const parsed = Number(value);
    if (Number.isFinite(parsed)) {
      return parsed;
    }
  }

  return null;
}

function packageHasRemainingEvents(pkg: TenantPackageSummary): boolean {
  const remaining = toNumber(pkg.remaining_events);

  if (pkg.package_type !== 'reseller') {
    if (remaining !== null) {
      return remaining > 0;
    }

    const usedEvents = toNumber(pkg.used_events) ?? 0;
    return usedEvents < 1;
  }

  if (remaining !== null) {
    return remaining > 0;
  }

  const limits = (pkg.package_limits ?? {}) as Record<string, unknown>;
  const limitMaxEvents = toNumber(limits.max_events_per_year);
  if (limitMaxEvents === null) {
    return false;
  }

  const usedEvents = toNumber(pkg.used_events) ?? 0;
  return limitMaxEvents > usedEvents;
}

function resolveEventSearchName(name: TenantEvent['name'], t: (key: string) => string): string {
  if (typeof name === 'string') return name;
  if (name && typeof name === 'object') {
    const values = Object.values(name).filter((value) => typeof value === 'string');
    if (values.length > 0) {
      return values.join(' ');
    }
  }
  return t('events.placeholders.untitled');
}

function resolveLocation(event: TenantEvent, t: (key: string) => 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 (candidate && candidate.trim()) {
    return candidate;
  }
  return t('events.detail.locationPlaceholder');
}

function formatDate(iso: string | null, t: (key: string) => string, locale?: string): string {
  const fallback = t('events.detail.dateTbd');
  if (!iso) return fallback;
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) {
    return fallback;
  }
  return date.toLocaleDateString(locale || undefined, { month: 'short', day: 'numeric', year: 'numeric' });
}
