import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { getEventQrInvites, updateEventQrInvite } from '../../api';
import { CANVAS_HEIGHT, CANVAS_WIDTH } from '../invite-layout/schema';

const fixtures = vi.hoisted(() => ({
  event: {
    id: 1,
    name: 'Demo Event',
    slug: 'demo-event',
  },
  invites: [
    {
      id: 1,
      url: 'https://example.test/guest/demo-event',
      qr_code_data_url: '',
      layouts: [
        {
          id: 'layout-1',
          name: 'Poster Layout',
          description: 'Layout description',
          paper: 'a4',
          orientation: 'portrait',
          panel_mode: 'single',
        },
      ],
    },
  ],
}));

const exportUtilsMock = vi.hoisted(() => ({
  generatePdfBytes: vi.fn(),
  generatePngDataUrl: vi.fn().mockResolvedValue('data:image/png;base64,abc'),
  triggerDownloadFromBlob: vi.fn(),
  triggerDownloadFromDataUrl: vi.fn(),
}));

const translationMock = vi.hoisted(() => ({
  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('react-router-dom', () => ({
  useNavigate: () => vi.fn(),
  useParams: () => ({ slug: fixtures.event.slug, tokenId: '1' }),
  useSearchParams: () => [new URLSearchParams(), vi.fn()],
}));

vi.mock('react-i18next', () => ({
  useTranslation: () => translationMock,
}));

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

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

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

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

vi.mock('../../lib/fonts', () => ({
  useTenantFonts: () => ({ fonts: [] }),
  ensureFontLoaded: vi.fn(),
}));

vi.mock('react-hot-toast', () => ({
  default: {
    error: vi.fn(),
    success: vi.fn(),
  },
}));

vi.mock('../invite-layout/export-utils', () => exportUtilsMock);

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" disabled={disabled} onClick={onPress}>
      {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} />,
  MobileSelect: ({ children, ...props }: React.SelectHTMLAttributes<HTMLSelectElement>) => (
    <select {...props}>{children}</select>
  ),
}));

vi.mock('@tamagui/accordion', () => ({
  Accordion: Object.assign(
    ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
    {
      Item: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
      Trigger: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
      Content: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
    },
  ),
}));

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

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', () => ({
  ADMIN_COLORS: {
    primary: '#ff5a5f',
    accent: '#6d28d9',
    text: '#0f172a',
    backdrop: '#0f172a',
  },
  ADMIN_GRADIENTS: {
    softCard: 'linear-gradient(180deg, #fff, #f3f4f6)',
  },
  useAdminTheme: () => ({
    textStrong: '#0f172a',
    muted: '#64748b',
    border: '#e2e8f0',
    primary: '#ff5a5f',
    accentSoft: '#f5f3ff',
    successText: '#16a34a',
    surface: '#ffffff',
    surfaceMuted: '#f8fafc',
    overlay: 'rgba(15, 23, 42, 0.5)',
    shadow: 'rgba(15, 23, 42, 0.2)',
    danger: '#dc2626',
  }),
}));

import MobileQrLayoutCustomizePage from '../QrLayoutCustomizePage';

describe('MobileQrLayoutCustomizePage', () => {
  it('renders the layout customize stepper', async () => {
    render(<MobileQrLayoutCustomizePage />);

    expect(await screen.findByText('Hintergrund')).toBeInTheDocument();
    expect(screen.getByText('Text')).toBeInTheDocument();
    expect(screen.getByText('Vorschau')).toBeInTheDocument();
  });

  it('shows background presets for foldable layouts', async () => {
    const foldableInvite = {
      ...fixtures.invites[0],
      layouts: [
        {
          ...fixtures.invites[0].layouts[0],
          orientation: 'landscape',
          panel_mode: 'double-mirror',
        },
      ],
    };

    vi.mocked(getEventQrInvites).mockResolvedValueOnce([foldableInvite]);
    vi.mocked(updateEventQrInvite).mockResolvedValue(foldableInvite as any);

    render(<MobileQrLayoutCustomizePage />);

    expect(await screen.findByText('Blue Floral')).toBeInTheDocument();
  });

  it('scales foldable background panels to A5 halves', async () => {
    const foldableInvite = {
      ...fixtures.invites[0],
      metadata: {
        layout_customization: {
          background_preset: 'blue-floral',
        },
      },
      layouts: [
        {
          ...fixtures.invites[0].layouts[0],
          orientation: 'landscape',
          panel_mode: 'double-mirror',
        },
      ],
    };

    vi.mocked(getEventQrInvites).mockResolvedValueOnce([foldableInvite]);
    exportUtilsMock.generatePngDataUrl.mockResolvedValue('data:image/png;base64,abc');
    exportUtilsMock.generatePngDataUrl.mockClear();

    render(<MobileQrLayoutCustomizePage />);

    const presetButton = await screen.findByText('Blue Floral');
    fireEvent.click(presetButton);

    const nextButton = await screen.findByText('Weiter');
    fireEvent.click(nextButton);
    const previewButton = await screen.findByText('Vorschau');
    fireEvent.click(previewButton);

    await waitFor(() => expect(exportUtilsMock.generatePngDataUrl).toHaveBeenCalled());

    const options = exportUtilsMock.generatePngDataUrl.mock.calls.at(-1)?.[0];

    expect(options).toBeDefined();
    expect(options.backgroundImagePanels).toHaveLength(2);
    expect(options.backgroundImagePanels[0]).toMatchObject({
      centerX: CANVAS_HEIGHT / 4,
      centerY: CANVAS_WIDTH / 2,
      width: CANVAS_HEIGHT / 2,
      height: CANVAS_WIDTH,
      rotation: 0,
      mirrored: false,
    });
    expect(options.backgroundImagePanels[1]).toMatchObject({
      centerX: (CANVAS_HEIGHT / 4) * 3,
      centerY: CANVAS_WIDTH / 2,
      width: CANVAS_HEIGHT / 2,
      height: CANVAS_WIDTH,
      rotation: 0,
      mirrored: true,
    });
  });
});
