import React from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Bell, RefreshCcw } 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 { MobileShell } from './components/MobileShell';
import { MobileCard, PillBadge } from './components/Primitives';
import { GuestNotificationSummary, listGuestNotifications } from '../api';
import { isAuthError } from '../auth/tokens';
import { getApiErrorMessage } from '../lib/apiError';
import toast from 'react-hot-toast';
import { MobileSheet } from './components/Sheet';
import { getEvents, TenantEvent } from '../api';
import { useTheme } from '@tamagui/core';

type NotificationItem = {
  id: string;
  title: string;
  body: string;
  time: string;
  tone: 'info' | 'warning';
};

async function loadNotifications(slug?: string): Promise<NotificationItem[]> {
  try {
    const result = slug ? await listGuestNotifications(slug) : [];
    return (result ?? []).map((item: GuestNotificationSummary) => ({
      id: String(item.id),
      title: item.title || 'Notification',
      body: item.body ?? '',
      time: item.created_at ?? '',
      tone: item.type === 'support_tip' ? 'warning' : 'info',
    }));
  } catch (err) {
    throw err;
  }
}

export default function MobileNotificationsPage() {
  const navigate = useNavigate();
  const { t } = useTranslation('management');
  const search = new URLSearchParams(typeof window !== 'undefined' ? window.location.search : '');
  const slug = search.get('event') ?? undefined;
  const [notifications, setNotifications] = React.useState<NotificationItem[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const [events, setEvents] = React.useState<TenantEvent[]>([]);
  const [showEventPicker, setShowEventPicker] = React.useState(false);
  const theme = useTheme();
  const text = String(theme.color?.val ?? '#111827');
  const muted = String(theme.gray?.val ?? '#4b5563');
  const border = String(theme.borderColor?.val ?? '#e5e7eb');
  const warningBg = String(theme.yellow3?.val ?? '#fef3c7');
  const warningIcon = String(theme.yellow11?.val ?? '#92400e');
  const infoBg = String(theme.blue3?.val ?? '#e0f2fe');
  const infoIcon = String(theme.primary?.val ?? '#2563eb');
  const errorText = String(theme.red10?.val ?? '#b91c1c');
  const primary = String(theme.primary?.val ?? '#007AFF');

  const reload = React.useCallback(async () => {
    setLoading(true);
    try {
      const data = await loadNotifications(slug ?? undefined);
      setNotifications(data);
      setError(null);
    } catch (err) {
      if (!isAuthError(err)) {
        const message = getApiErrorMessage(err, t('events.errors.loadFailed', 'Benachrichtigungen konnten nicht geladen werden.'));
        setError(message);
        toast.error(message);
      }
    } finally {
      setLoading(false);
    }
  }, [slug, t]);

  React.useEffect(() => {
    void reload();
  }, [reload]);

  React.useEffect(() => {
    (async () => {
      try {
        const list = await getEvents();
        setEvents(list);
      } catch {
        // non-fatal
      }
    })();
  }, []);

  return (
    <MobileShell
      activeTab="home"
      title={t('mobileNotifications.title', 'Notifications')}
      onBack={() => navigate(-1)}
      headerActions={
        <Pressable onPress={() => reload()}>
          <RefreshCcw size={18} color={text} />
        </Pressable>
      }
    >
      {error ? (
        <MobileCard>
          <Text fontWeight="700" color={errorText}>
            {error}
          </Text>
        </MobileCard>
      ) : null}

      {loading ? (
        <YStack space="$2">
          {Array.from({ length: 4 }).map((_, idx) => (
            <MobileCard key={`al-${idx}`} height={70} opacity={0.6} />
          ))}
        </YStack>
      ) : notifications.length === 0 ? (
        <MobileCard alignItems="center" justifyContent="center" space="$2">
          <Bell size={24} color={String(theme.gray9?.val ?? '#9ca3af')} />
          <Text fontSize="$sm" color={muted}>
            {t('mobileNotifications.empty', 'Keine Benachrichtigungen vorhanden.')}
          </Text>
        </MobileCard>
      ) : (
        <YStack space="$2">
          {events.length ? (
            <Pressable onPress={() => setShowEventPicker(true)}>
              <Text fontSize="$sm" color={primary} fontWeight="700">
                {t('mobileNotifications.filterByEvent', 'Nach Event filtern')}
              </Text>
            </Pressable>
          ) : null}
          {notifications.map((item) => (
            <MobileCard key={item.id} space="$2">
              <XStack alignItems="center" space="$2">
                <XStack
                  width={36}
                  height={36}
                  borderRadius={12}
                  alignItems="center"
                  justifyContent="center"
                  backgroundColor={item.tone === 'warning' ? warningBg : infoBg}
                >
                  <Bell size={18} color={item.tone === 'warning' ? warningIcon : infoIcon} />
                </XStack>
                <YStack space="$0.5" flex={1}>
                  <Text fontSize="$sm" fontWeight="700" color={text}>
                    {item.title}
                  </Text>
                  <Text fontSize="$xs" color={muted}>
                    {item.body}
                  </Text>
                </YStack>
                <PillBadge tone={item.tone === 'warning' ? 'warning' : 'muted'}>{item.time}</PillBadge>
              </XStack>
            </MobileCard>
          ))}
        </YStack>
      )}

      <MobileSheet
        open={showEventPicker}
        onClose={() => setShowEventPicker(false)}
        title={t('mobileNotifications.filterByEvent', 'Nach Event filtern')}
        footer={null}
      >
        <YStack space="$2">
          {events.length === 0 ? (
            <Text fontSize="$sm" color={muted}>
              {t('events.list.empty.description', 'Starte jetzt mit deinem ersten Event.')}
            </Text>
          ) : (
            events.map((ev) => (
              <Pressable
                key={ev.slug}
                onPress={() => {
                  setShowEventPicker(false);
                  if (ev.slug) {
                    navigate(`/admin/mobile/notifications?event=${ev.slug}`);
                  }
                }}
              >
                <XStack alignItems="center" justifyContent="space-between" paddingVertical="$2">
                  <YStack>
                    <Text fontSize="$sm" fontWeight="700" color={text}>
                      {ev.name}
                    </Text>
                    <Text fontSize="$xs" color={muted}>
                      {ev.slug}
                    </Text>
                  </YStack>
                  <PillBadge tone="muted">{ev.status ?? '—'}</PillBadge>
                </XStack>
              </Pressable>
            ))
          )}
        </YStack>
      </MobileSheet>
    </MobileShell>
  );
}
