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 { MobileScaffold } from './components/Scaffold';
import { MobileCard, PillBadge } from './components/Primitives';
import { BottomNav } from './components/BottomNav';
import { GuestNotificationSummary, listGuestNotifications } from '../api';
import { isAuthError } from '../auth/tokens';
import { getApiErrorMessage } from '../lib/apiError';
import toast from 'react-hot-toast';
import { useMobileNav } from './hooks/useMobileNav';
import { MobileSheet } from './components/Sheet';
import { getEvents, TenantEvent } from '../api';

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

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

export default function MobileAlertsPage() {
  const navigate = useNavigate();
  const { t } = useTranslation('management');
  const search = new URLSearchParams(typeof window !== 'undefined' ? window.location.search : '');
  const slug = search.get('event') ?? undefined;
  const [alerts, setAlerts] = React.useState<AlertItem[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const { go } = useMobileNav(slug ?? null);
  const [events, setEvents] = React.useState<TenantEvent[]>([]);
  const [showEventPicker, setShowEventPicker] = React.useState(false);

  const reload = React.useCallback(async () => {
    setLoading(true);
    try {
      const data = await loadNotifications(slug ?? undefined);
      setAlerts(data);
      setError(null);
    } catch (err) {
      if (!isAuthError(err)) {
        const message = getApiErrorMessage(err, t('events.errors.loadFailed', 'Alerts 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 (
    <MobileScaffold
      title={t('alerts.title', 'Alerts')}
      onBack={() => navigate(-1)}
      rightSlot={
        <Pressable onPress={() => reload()}>
          <RefreshCcw size={18} color="#0f172a" />
        </Pressable>
      }
      footer={
        <BottomNav active="home" onNavigate={go} />
      }
    >
      {error ? (
        <MobileCard>
          <Text fontWeight="700" color="#b91c1c">
            {error}
          </Text>
        </MobileCard>
      ) : null}

      {loading ? (
        <YStack space="$2">
          {Array.from({ length: 4 }).map((_, idx) => (
            <MobileCard key={`al-${idx}`} height={70} opacity={0.6} />
          ))}
        </YStack>
      ) : alerts.length === 0 ? (
        <MobileCard alignItems="center" justifyContent="center" space="$2">
          <Bell size={24} color="#9ca3af" />
          <Text fontSize="$sm" color="#4b5563">
            {t('alerts.empty', 'Keine Alerts vorhanden.')}
          </Text>
        </MobileCard>
      ) : (
        <YStack space="$2">
          {events.length ? (
            <Pressable onPress={() => setShowEventPicker(true)}>
              <Text fontSize="$sm" color="#007AFF" fontWeight="700">
                {t('alerts.filterByEvent', 'Filter by event')}
              </Text>
            </Pressable>
          ) : null}
          {alerts.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' ? '#fef3c7' : '#e0f2fe'}
                >
                  <Bell size={18} color={item.tone === 'warning' ? '#92400e' : '#2563eb'} />
                </XStack>
                <YStack space="$0.5" flex={1}>
                  <Text fontSize="$sm" fontWeight="700" color="#111827">
                    {item.title}
                  </Text>
                  <Text fontSize="$xs" color="#4b5563">
                    {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('alerts.filterByEvent', 'Filter by event')}
        footer={null}
      >
        <YStack space="$2">
          {events.length === 0 ? (
            <Text fontSize="$sm" color="#4b5563">
              {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/alerts?event=${ev.slug}`);
                  }
                }}
              >
                <XStack alignItems="center" justifyContent="space-between" paddingVertical="$2">
                  <YStack>
                    <Text fontSize="$sm" fontWeight="700" color="#111827">
                      {ev.name}
                    </Text>
                    <Text fontSize="$xs" color="#6b7280">
                      {ev.slug}
                    </Text>
                  </YStack>
                  <PillBadge tone="muted">{ev.status ?? '—'}</PillBadge>
                </XStack>
              </Pressable>
            ))
          )}
        </YStack>
      </MobileSheet>
    </MobileScaffold>
  );
}
