import React from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Download, Share2, ChevronRight, 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, CTAButton, PillBadge } from './components/Primitives';
import { TenantEvent, getEvent, getEventQrInvites, createQrInvite } from '../api';
import { isAuthError } from '../auth/tokens';
import { getApiErrorMessage } from '../lib/apiError';
import toast from 'react-hot-toast';
import { MobileSheet } from './components/Sheet';

const LAYOUTS = [
  { key: 'badges', title: 'Badges', subtitle: 'Standard, Staff' },
  { key: 'tents', title: 'Table Tents', subtitle: 'A4, Letter' },
  { key: 'posters', title: 'Posters', subtitle: 'A3, 11x17' },
  { key: 'programs', title: 'Event Programs', subtitle: 'Folded, Booklet' },
];

export default function MobileQrPrintPage() {
  const { slug: slugParam } = useParams<{ slug?: string }>();
  const slug = slugParam ?? null;
  const navigate = useNavigate();
  const { t } = useTranslation('management');

  const [event, setEvent] = React.useState<TenantEvent | null>(null);
  const [error, setError] = React.useState<string | null>(null);
  const [loading, setLoading] = React.useState(true);
  const [paperSize, setPaperSize] = React.useState('A4 (210 x 297 mm)');
  const [qrUrl, setQrUrl] = React.useState<string>('');
  const [showPaperSheet, setShowPaperSheet] = React.useState(false);
  const [showLayoutSheet, setShowLayoutSheet] = React.useState(false);

  React.useEffect(() => {
    if (!slug) return;
    (async () => {
      setLoading(true);
      try {
        const data = await getEvent(slug);
        const invites = await getEventQrInvites(slug);
        setEvent(data);
        const primaryInvite = invites.find((item) => item.is_active) ?? invites[0];
        setQrUrl(primaryInvite?.url ?? data.public_url ?? '');
        setError(null);
      } catch (err) {
        if (!isAuthError(err)) {
          setError(getApiErrorMessage(err, t('events.errors.loadFailed', 'QR-Daten konnten nicht geladen werden.')));
        }
      } finally {
        setLoading(false);
      }
    })();
  }, [slug, t]);

  return (
    <MobileShell
      activeTab="home"
      title={t('events.qr.title', 'QR Code & Print Layouts')}
      onBack={() => navigate(-1)}
      headerActions={
        <Pressable onPress={() => window.location.reload()}>
          <RefreshCcw size={18} color="#0f172a" />
        </Pressable>
      }
    >
      {error ? (
        <MobileCard>
          <Text fontWeight="700" color="#b91c1c">
            {error}
          </Text>
        </MobileCard>
      ) : null}

      <MobileCard space="$3" alignItems="center">
        <Text fontSize="$md" fontWeight="800" color="#111827">
          {t('events.qr.heroTitle', 'Entrance QR Code')}
        </Text>
        <YStack
          width={180}
          height={180}
          borderRadius={16}
          borderWidth={1}
          borderColor="#e5e7eb"
          backgroundColor="#f8fafc"
          alignItems="center"
          justifyContent="center"
          overflow="hidden"
        >
          {qrUrl ? (
            <img
              src={`https://api.qrserver.com/v1/create-qr-code/?size=220x220&data=${encodeURIComponent(qrUrl)}`}
              alt="QR"
              style={{ width: '100%', height: '100%', objectFit: 'contain' }}
            />
          ) : (
            <Text color="#9ca3af" fontSize="$sm">
              {t('events.qr.missing', 'Kein QR-Link vorhanden')}
            </Text>
          )}
        </YStack>
        <Text fontSize="$xs" color="#6b7280">
          {t('events.qr.description', 'Scan to access the event guest app.')}
        </Text>
        <XStack space="$2" width="100%" marginTop="$2">
          <CTAButton
            label={t('events.qr.download', 'Download')}
            onPress={() => {
              if (qrUrl) {
                toast.success(t('events.qr.downloadStarted', 'Download gestartet'));
              } else {
                toast.error(t('events.qr.missing', 'Kein QR-Link vorhanden'));
              }
            }}
          />
          <CTAButton
            label={t('events.qr.share', 'Share')}
            onPress={async () => {
              try {
                const shareUrl = String(qrUrl || (event as any)?.public_url || '');
                await navigator.clipboard.writeText(shareUrl);
                toast.success(t('events.qr.shareSuccess', 'Link kopiert'));
              } catch {
                toast.error(t('events.qr.shareFailed', 'Konnte Link nicht kopieren'));
              }
            }}
          />
        </XStack>
      </MobileCard>

      <MobileCard space="$2">
        <Text fontSize="$md" fontWeight="800" color="#111827">
          {t('events.qr.layouts', 'Print Layouts')}
        </Text>
        <YStack space="$1">
          {LAYOUTS.map((layout) => (
            <XStack
              key={layout.key}
              alignItems="center"
              justifyContent="space-between"
              paddingVertical="$2"
              borderBottomWidth={layout.key === 'programs' ? 0 : 1}
              borderColor="#e5e7eb"
              onPress={() => setShowLayoutSheet(true)}
            >
              <YStack>
                <Text fontSize="$sm" fontWeight="700" color="#111827">
                  {layout.title}
                </Text>
                <Text fontSize="$xs" color="#6b7280">
                  {layout.subtitle}
                </Text>
              </YStack>
              <ChevronRight size={16} color="#9ca3af" />
            </XStack>
          ))}
        </YStack>
      </MobileCard>

      <MobileCard space="$2">
        <Text fontSize="$sm" fontWeight="700" color="#111827">
          {t('events.qr.templates', 'Templates')}
        </Text>
        <XStack justifyContent="space-between" alignItems="center" paddingVertical="$2" borderBottomWidth={1} borderColor="#e5e7eb">
          <Text fontSize="$sm" color="#111827">
            {t('events.qr.branding', 'Branding')}
          </Text>
          <label style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <input type="checkbox" defaultChecked />
            <Text fontSize="$sm" color="#111827">
              {t('common.enabled', 'Enabled')}
            </Text>
          </label>
        </XStack>
        <Pressable onPress={() => setShowPaperSheet(true)}>
          <XStack justifyContent="space-between" alignItems="center" paddingVertical="$2">
            <Text fontSize="$sm" color="#111827">
              {t('events.qr.paper', 'Paper Size')}
            </Text>
            <XStack alignItems="center" space="$2">
              <Text fontSize="$sm" color="#111827">
                {paperSize}
              </Text>
              <ChevronRight size={16} color="#9ca3af" />
            </XStack>
          </XStack>
        </Pressable>
        <CTAButton
          label={t('events.qr.preview', 'Preview & Print')}
          onPress={() => toast.success(t('events.qr.previewStarted', 'Preview gestartet (mock)'))}
        />
        <CTAButton
          label={t('events.qr.createLink', 'Neuen QR-Link erstellen')}
          onPress={async () => {
            if (!slug) return;
            try {
                if (!slug) return;
                const invite = await createQrInvite(slug, { label: 'Mobile Link' });
              setQrUrl(invite.url);
              toast.success(t('events.qr.created', 'Neuer QR-Link erstellt'));
            } catch (err) {
              toast.error(getApiErrorMessage(err, t('events.qr.createFailed', 'Link konnte nicht erstellt werden.')));
            }
          }}
        />
      </MobileCard>

      <MobileSheet
        open={showPaperSheet}
        onClose={() => setShowPaperSheet(false)}
        title={t('events.qr.paper', 'Paper Size')}
        footer={null}
      >
        <YStack space="$2">
          {['A4 (210 x 297 mm)', 'Letter (8.5 x 11 in)', 'A3 (297 x 420 mm)'].map((size) => (
            <Pressable
              key={size}
              onPress={() => {
                setPaperSize(size);
                setShowPaperSheet(false);
              }}
            >
              <XStack alignItems="center" justifyContent="space-between" paddingVertical="$2">
                <Text fontSize="$sm" color="#111827">
                  {size}
                </Text>
                {paperSize === size ? <ChevronRight size={16} color="#007AFF" /> : null}
              </XStack>
            </Pressable>
          ))}
        </YStack>
      </MobileSheet>

      <MobileSheet
        open={showLayoutSheet}
        onClose={() => setShowLayoutSheet(false)}
        title={t('events.qr.layouts', 'Print Layouts')}
        footer={
          <CTAButton
            label={t('events.qr.preview', 'Preview & Print')}
            onPress={() => toast.success(t('events.qr.previewStarted', 'Preview gestartet (mock)'))}
          />
        }
      >
        <YStack space="$2">
          {LAYOUTS.map((layout) => (
            <MobileCard key={`lay-${layout.key}`} padding="$3" borderColor="#e5e7eb">
              <XStack alignItems="center" justifyContent="space-between">
                <YStack>
                  <Text fontSize="$sm" fontWeight="700" color="#111827">
                    {layout.title}
                  </Text>
                  <Text fontSize="$xs" color="#6b7280">
                    {layout.subtitle}
                  </Text>
                </YStack>
                <PillBadge tone="muted">{paperSize}</PillBadge>
              </XStack>
            </MobileCard>
          ))}
        </YStack>
      </MobileSheet>
    </MobileShell>
  );
}
