import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

const fixtures = vi.hoisted(() => ({
  event: {
    id: 1,
    name: 'Demo Event',
    slug: 'demo-event',
    public_url: 'https://example.test/guest/demo-event',
  },
  invites: [
    {
      id: 10,
      url: 'https://example.test/guest/demo-event',
      qr_code_data_url: 'data:image/png;base64,abc',
      is_active: true,
      layouts: [
        {
          id: 'layout-1',
          panel_mode: 'single',
          orientation: 'portrait',
        },
      ],
    },
  ],
}));

vi.mock('react-router-dom', () => ({
  useNavigate: () => vi.fn(),
  useParams: () => ({ slug: fixtures.event.slug }),
}));

vi.mock('react-i18next', () => ({
  useTranslation: () => ({
    t: (key: string, fallback?: string | Record<string, unknown>) => {
      if (typeof fallback === 'string') {
        return fallback;
      }
      if (fallback && typeof fallback === 'object' && typeof fallback.defaultValue === 'string') {
        return fallback.defaultValue;
      }
      return key;
    },
  }),
}));

vi.mock('../hooks/useBackNavigation', () => ({
  useBackNavigation: () => undefined,
}));

vi.mock('../../api', () => ({
  getEvent: vi.fn().mockResolvedValue(fixtures.event),
  getEventQrInvites: vi.fn().mockResolvedValue(fixtures.invites),
  createQrInvite: vi.fn(),
}));

vi.mock('../../auth/tokens', () => ({
  isAuthError: () => false,
}));

vi.mock('../../lib/apiError', () => ({
  getApiErrorMessage: () => 'error',
}));

vi.mock('./qr/utils', () => ({
  resolveLayoutForFormat: () => 'layout-1',
}));

vi.mock('../components/MobileShell', () => ({
  MobileShell: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  HeaderActionButton: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));

vi.mock('../components/Primitives', () => ({
  MobileCard: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  CTAButton: ({ label, onPress, disabled }: { label: string; onPress?: () => void; disabled?: boolean }) => (
    <button type="button" onClick={onPress} disabled={disabled}>
      {label}
    </button>
  ),
  PillBadge: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));

vi.mock('../components/FormControls', () => ({
  MobileInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
  MobileTextArea: (props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) => <textarea {...props} />,
}));

vi.mock('@tamagui/stacks', () => ({
  YStack: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  XStack: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));

vi.mock('@tamagui/text', () => ({
  SizableText: ({ children }: { children: React.ReactNode }) => <span>{children}</span>,
}));

vi.mock('@tamagui/react-native-web-lite', () => ({
  Pressable: ({ children, onPress }: { children: React.ReactNode; onPress?: () => void }) => (
    <button type="button" onClick={onPress}>
      {children}
    </button>
  ),
}));

vi.mock('../theme', () => ({
  useAdminTheme: () => ({
    text: '#111827',
    muted: '#6b7280',
    subtle: '#94a3b8',
    border: '#e5e7eb',
    primary: '#ff5a5f',
    danger: '#dc2626',
    surface: '#ffffff',
    surfaceMuted: '#f9fafb',
    accentSoft: '#eef2ff',
    textStrong: '#0f172a',
  }),
}));

import MobileQrPrintPage from '../QrPrintPage';
import { createQrInvite } from '../../api';

describe('MobileQrPrintPage', () => {
  it('renders QR overview content', async () => {
    render(<MobileQrPrintPage />);

    expect(await screen.findByText('Entrance QR Code')).toBeInTheDocument();
    expect(screen.getByText('Schritt 1: Format wählen')).toBeInTheDocument();
    expect(screen.getAllByText('Neuen QR-Link erstellen').length).toBeGreaterThan(0);
  });

  it('requires confirmation before creating a new QR link', async () => {
    const user = userEvent.setup();
    const confirmSpy = vi.fn().mockReturnValue(false);
    window.confirm = confirmSpy;

    render(<MobileQrPrintPage />);

    const createButton = await screen.findByRole('button', { name: 'Neuen QR-Link erstellen' });
    await user.click(createButton);

    expect(confirmSpy).toHaveBeenCalled();
    expect(confirmSpy).toHaveBeenCalledWith(expect.stringContaining('Ausdrucke'));
    expect(createQrInvite).not.toHaveBeenCalled();
  });
});
