import React from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Check, Copy, Download, Share2, Sparkles, Trophy, Users } 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 { Switch } from '@tamagui/switch';
import { MobileShell } from './components/MobileShell';
import { MobileCard, CTAButton, PillBadge, SkeletonCard } from './components/Primitives';
import { LegalConsentSheet } from './components/LegalConsentSheet';
import {
  getEvent,
  getEventStats,
  getEventQrInvites,
  updateEvent,
  TenantEvent,
  EventStats,
  EventQrInvite,
  EventAddonCatalogItem,
  getAddonCatalog,
  createEventAddonCheckout,
} from '../api';
import { isAuthError } from '../auth/tokens';
import { getApiErrorMessage } from '../lib/apiError';
import { adminPath } from '../constants';
import toast from 'react-hot-toast';
import { useBackNavigation } from './hooks/useBackNavigation';
import { useAdminTheme } from './theme';

type GalleryCounts = {
  photos: number;
  likes: number;
  pending: number;
};

export default function MobileEventRecapPage() {
  const { slug } = useParams<{ slug: string }>();
  const navigate = useNavigate();
  const { t } = useTranslation('management');
  const { textStrong, text, muted, border, primary, successText, danger } = useAdminTheme();

  const [event, setEvent] = React.useState<TenantEvent | null>(null);
  const [stats, setEventStats] = React.useState<EventStats | null>(null);
  const [invites, setInvites] = React.useState<EventQrInvite[]>([]);
  const [addons, setAddons] = React.useState<EventAddonCatalogItem[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const [consentOpen, setConsentOpen] = React.useState(false);
  const [busyScope, setBusyScope] = React.useState<string | null>(null);
  const back = useBackNavigation(slug ? adminPath(`/mobile/events/${slug}`) : adminPath('/mobile/events'));

  const load = React.useCallback(async () => {
    if (!slug) return;
    setLoading(true);
    try {
      const [eventData, statsData, invitesData, addonsData] = await Promise.all([
        getEvent(slug),
        getEventStats(slug),
        getEventQrInvites(slug),
        getAddonCatalog(),
      ]);
      setEvent(eventData);
      setEventStats(statsData);
      setInvites(invitesData);
      setAddons(addonsData);
      setError(null);
    } catch (err) {
      if (!isAuthError(err)) {
        setError(getApiErrorMessage(err, t('events.errors.loadFailed', 'Recap konnte nicht geladen werden.')));
      }
    } finally {
      setLoading(false);
    }
  }, [slug, t]);

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

  const handleCheckout = async (addonKey: string) => {
    if (!slug || busyScope) return;
    setBusyScope(addonKey);
    try {
      const { checkout_url } = await createEventAddonCheckout(slug, {
        addon_key: addonKey,
        success_url: window.location.href,
        cancel_url: window.location.href,
      });
      if (checkout_url) {
        window.location.href = checkout_url;
      }
    } catch (err) {
      toast.error(getApiErrorMessage(err, t('events.errors.checkoutFailed', 'Bezahlvorgang konnte nicht gestartet werden.')));
      setBusyScope(null);
    }
  };

  const handleConsentConfirm = async (consents: { acceptedTerms: boolean }) => {
    if (!slug || !busyScope) return;
    try {
      const { checkout_url } = await createEventAddonCheckout(slug, {
        addon_key: busyScope,
        success_url: window.location.href,
        cancel_url: window.location.href,
        accepted_terms: consents.acceptedTerms,
      } as any);
      if (checkout_url) {
        window.location.href = checkout_url;
      }
    } catch (err) {
      toast.error(getApiErrorMessage(err, t('events.errors.checkoutFailed', 'Bezahlvorgang konnte nicht gestartet werden.')));
      setBusyScope(null);
      setConsentOpen(false);
    }
  };

  if (loading) {
    return (
      <MobileShell activeTab="home" title={t('events.recap.title', 'Event Recap')} onBack={back}>
        <YStack space="$3">
          <SkeletonCard height={120} />
          <SkeletonCard height={200} />
          <SkeletonCard height={150} />
        </YStack>
      </MobileShell>
    );
  }

  if (error || !event) {
    return (
      <MobileShell activeTab="home" title={t('events.recap.title', 'Event Recap')} onBack={back}>
        <MobileCard>
          <Text fontWeight="700" color={danger}>
            {error || t('common.error', 'Ein Fehler ist aufgetreten.')}
          </Text>
          <CTAButton label={t('common.retry', 'Erneut versuchen')} onPress={load} tone="ghost" />
        </MobileCard>
      </MobileShell>
    );
  }

  const galleryCounts: GalleryCounts = {
    photos: stats?.total ?? 0,
    likes: stats?.likes ?? 0,
    pending: stats?.pending_photos ?? 0,
  };

  const activeInvite = invites.find((i) => i.is_active) ?? invites[0] ?? null;
  const guestLink = activeInvite?.url ?? '';

  return (
    <MobileShell
      activeTab="home"
      title={t('events.recap.title', 'Event Recap')}
      onBack={back}
    >
      <YStack space="$4">
        {/* Status & Summary */}
        <MobileCard space="$3">
          <XStack alignItems="center" justifyContent="space-between">
            <YStack space="$1">
              <Text fontSize="$xl" fontWeight="800" color={textStrong}>
                {t('events.recap.done', 'Event beendet')}
              </Text>
              <Text fontSize="$sm" color={muted}>
                {formatDate(event.event_date)}
              </Text>
            </YStack>
            <PillBadge tone="success">{t('events.recap.statusClosed', 'Archiviert')}</PillBadge>
          </XStack>

          <XStack flexWrap="wrap" gap="$2" marginTop="$1">
            <Stat label={t('events.stats.uploads', 'Uploads')} value={String(galleryCounts.photos)} />
            <Stat label={t('events.stats.pending', 'Offen')} value={String(galleryCounts.pending)} />
            <Stat label={t('events.stats.likes', 'Likes')} value={String(galleryCounts.likes)} />
          </XStack>
        </MobileCard>

        {/* Share Section */}
        <MobileCard space="$3">
          <XStack alignItems="center" space="$2">
            <Share2 size={18} color={primary} />
            <Text fontSize="$md" fontWeight="800" color={textStrong}>
              {t('events.recap.shareGallery', 'Galerie teilen')}
            </Text>
          </XStack>
          <Text fontSize="$sm" color={text}>
            {t('events.recap.shareBody', 'Deine Gäste können die Galerie auch nach dem Event weiterhin ansehen.')}
          </Text>

          <YStack space="$2" marginTop="$1">
            <XStack
              backgroundColor={border}
              padding="$3"
              borderRadius={12}
              alignItems="center"
              justifyContent="space-between"
            >
              <Text fontSize="$xs" color={muted} numberOfLines={1} flex={1}>
                {guestLink}
              </Text>
              <CTAButton label={t('events.recap.copy', 'Kopieren')} tone="ghost" onPress={() => guestLink && copyToClipboard(guestLink, t)} />
            </XStack>
            {typeof navigator !== 'undefined' && !!navigator.share && (
                <CTAButton label={t('events.recap.share', 'Teilen')} tone="ghost" onPress={() => shareLink(guestLink, event, t)} />
            )}
          </YStack>

          {activeInvite?.qr_code_data_url ? (
            <YStack alignItems="center" space="$2" marginTop="$2">
                <YStack
                    padding="$2"
                    backgroundColor="white"
                    borderRadius={12}
                    borderWidth={1}
                    borderColor={border}
                >
                    <img src={activeInvite.qr_code_data_url} alt="QR" style={{ width: 120, height: 120 }} />
                </YStack>
                <CTAButton label={t('events.recap.downloadQr', 'QR herunterladen')} tone="ghost" onPress={() => downloadQr(activeInvite.qr_code_data_url!)} />
            </YStack>
          ) : null}
        </MobileCard>

        {/* Settings */}
        <MobileCard space="$3">
          <XStack alignItems="center" space="$2">
            <Users size={18} color={primary} />
            <Text fontSize="$md" fontWeight="800" color={textStrong}>
              {t('events.recap.settings', 'Nachlauf-Optionen')}
            </Text>
          </XStack>

          <YStack space="$1.5">
            <ToggleOption
              label={t('events.recap.allowDownloads', 'Gäste dürfen Fotos laden')}
              value={Boolean(event.settings?.guest_downloads_enabled)}
              onToggle={(value) => updateSetting(event, setEvent, slug, 'guest_downloads_enabled', value, setError, t as any)}
            />
            <ToggleOption
              label={t('events.recap.allowSharing', 'Gäste dürfen Fotos teilen')}
              value={Boolean(event.settings?.guest_sharing_enabled)}
              onToggle={(value) => updateSetting(event, setEvent, slug, 'guest_sharing_enabled', value, setError, t as any)}
            />
          </YStack>
        </MobileCard>

        {/* Extensions */}
        <MobileCard space="$3">
          <XStack alignItems="center" space="$2">
            <Sparkles size={18} color={primary} />
            <Text fontSize="$md" fontWeight="800" color={textStrong}>
              {t('events.recap.addons', 'Galerie verlängern')}
            </Text>
          </XStack>
          <Text fontSize="$sm" color={text}>
            {t('events.recap.addonBody', 'Die Online-Zeit deiner Galerie neigt sich dem Ende? Hier kannst du sie verlängern.')}
          </Text>
          
          <YStack space="$2">
            {addons
              .filter((a) => a.key === 'gallery_extension')
              .map((addon) => (
                <CTAButton
                  key={addon.key}
                  label={t('events.recap.buyExtension', 'Galerie um 30 Tage verlängern')}
                  onPress={() => handleCheckout(addon.key)}
                  loading={busyScope === addon.key}
                />
              ))}
          </YStack>
        </MobileCard>
      </YStack>

      <LegalConsentSheet
        open={consentOpen}
        onClose={() => {
          setConsentOpen(false);
          setBusyScope(null);
        }}
        onConfirm={handleConsentConfirm}
        busy={Boolean(busyScope)}
        t={t as any}
      />
    </MobileShell>
  );
}

function Stat({ label, value, pill }: { label: string; value: string; pill?: boolean }) {
  const { textStrong, muted, accentSoft, border } = useAdminTheme();
  return (
    <YStack
      paddingHorizontal="$3"
      paddingVertical="$2"
      borderRadius={12}
      borderWidth={1}
      borderColor={border}
      backgroundColor={pill ? accentSoft : 'transparent'}
      minWidth={80}
    >
      <Text fontSize="$xs" color={muted}>
        {label}
      </Text>
      <Text fontSize="$md" fontWeight="800" color={textStrong}>
        {value}
      </Text>
    </YStack>
  );
}

function ToggleOption({ label, value, onToggle }: { label: string; value: boolean; onToggle: (val: boolean) => void }) {
  const { textStrong } = useAdminTheme();
  return (
    <XStack alignItems="center" justifyContent="space-between" paddingVertical="$1">
      <Text fontSize="$sm" color={textStrong} fontWeight="600">
        {label}
      </Text>
      <Switch size="$4" checked={value} onCheckedChange={onToggle} aria-label={label}>
        <Switch.Thumb />
      </Switch>
    </XStack>
  );
}

async function updateSetting(
  event: TenantEvent,
  setEvent: (event: TenantEvent) => void,
  slug: string | undefined,
  key: 'guest_downloads_enabled' | 'guest_sharing_enabled',
  value: boolean,
  setError: (message: string | null) => void,
  t: (key: string, fallback?: string) => string,
): Promise<void> {
  if (!slug) return;
  try {
    const updated = await updateEvent(slug, {
      settings: {
        ...(event.settings ?? {}),
        [key]: value,
      },
    });
    setEvent(updated);
  } catch (err) {
    if (!isAuthError(err)) {
      setError(getApiErrorMessage(err, t('events.errors.toggleFailed', 'Einstellung konnte nicht gespeichert werden.')));
    }
  }
}

function copyToClipboard(value: string, t: any) {
  if (typeof window !== 'undefined') {
    void window.navigator.clipboard.writeText(value);
    toast.success(t('events.recap.copySuccess', 'Link kopiert'));
  }
}

async function shareLink(value: string, event: TenantEvent | null, t: any) {
  if (typeof window !== 'undefined' && navigator.share) {
    try {
      await navigator.share({
        title: resolveName(event?.name ?? ''),
        text: t('events.recap.shareText', 'Schau dir die Fotos von unserem Event an!'),
        url: value,
      });
    } catch {
      // silently ignore or fallback to copy
    }
  }
}

function downloadQr(dataUrl: string) {
  const link = document.createElement('a');
  link.href = dataUrl;
  link.download = 'guest-gallery-qr.png';
  link.click();
}

function resolveName(name: TenantEvent['name']): string {
  if (typeof name === 'string') return name;
  if (name && typeof name === 'object') {
    return name.de ?? name.en ?? Object.values(name)[0] ?? 'Event';
  }
  return 'Event';
}

function formatDate(iso?: string | null): string {
  if (!iso) return '';
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return '';
  return date.toLocaleDateString(undefined, { day: '2-digit', month: 'short', year: 'numeric' });
}
