import React from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';

const navigateMock = vi.fn();

const fixtures = vi.hoisted(() => ({
  event: {
    id: 77,
    name: { de: 'Sommerfest', en: 'Summer Fest' },
    slug: 'summer-fest',
    status: 'published',
    event_date: '2026-07-01T10:00:00Z',
    settings: {},
  },
  purchase: {
    id: 901,
    addon_key: 'extra_photos_500',
    label: 'Extra photos 500',
    quantity: 1,
    status: 'completed',
    amount: 12,
    currency: 'EUR',
    extra_photos: 500,
    extra_guests: 0,
    extra_gallery_days: 0,
    purchased_at: '2026-02-07T12:00:00Z',
    receipt_url: null,
    checkout_id: 'ORDER-123',
    transaction_id: 'TX-999',
    created_at: '2026-02-07T11:59:00Z',
    addon_intent: 'intent_abc',
    event: { id: 77, slug: 'summer-fest', name: { de: 'Sommerfest', en: 'Summer Fest' } },
  },
}));

vi.mock('react-router-dom', () => ({
  useNavigate: () => navigateMock,
  useParams: () => ({ slug: fixtures.event.slug }),
  useLocation: () => ({ pathname: '/event-admin/mobile/events/summer-fest/addons/success', search: '?addon_intent=intent_abc' }),
}));

vi.mock('react-i18next', () => ({
  useTranslation: () => ({
    t: (key: string, fallback?: string | Record<string, unknown>, options?: Record<string, unknown>) => {
      let value = typeof fallback === 'string' ? fallback : key;
      if (options) {
        Object.entries(options).forEach(([optionKey, optionValue]) => {
          value = value.replaceAll(`{{${optionKey}}}`, String(optionValue));
        });
      }
      return value;
    },
  }),
  initReactI18next: {
    type: '3rdParty',
    init: () => undefined,
  },
}));

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

vi.mock('../../lib/apiError', () => ({
  getApiErrorMessage: (_err: unknown, fallback: string) => fallback,
}));

vi.mock('../../lib/events', () => ({
  resolveEventDisplayName: (event: any) => event?.name?.de ?? event?.name ?? 'Event',
}));

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

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

vi.mock('../components/Primitives', () => ({
  MobileCard: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  CTAButton: ({ label, onPress }: { label: string; onPress?: () => void }) => (
    <button type="button" onClick={onPress}>{label}</button>
  ),
  PillBadge: ({ children }: { children: React.ReactNode }) => <span>{children}</span>,
  SkeletonCard: () => <div>Loading...</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('../../api', () => ({
  getEvent: vi.fn().mockResolvedValue(fixtures.event),
  getEventAddonPurchase: vi.fn().mockResolvedValue(fixtures.purchase),
}));

import MobileEventAddonSuccessPage from '../EventAddonSuccessPage';
import { getEventAddonPurchase } from '../../api';

describe('MobileEventAddonSuccessPage', () => {
  beforeEach(() => {
    vi.clearAllMocks();

    Object.defineProperty(window, 'matchMedia', {
      writable: true,
      value: vi.fn().mockReturnValue({
        matches: true,
        media: '(prefers-reduced-motion: reduce)',
        onchange: null,
        addListener: vi.fn(),
        removeListener: vi.fn(),
        addEventListener: vi.fn(),
        removeEventListener: vi.fn(),
        dispatchEvent: vi.fn(),
      }),
    });
  });

  it('loads purchase by addon intent and renders summary details', async () => {
    const purchaseMock = vi.mocked(getEventAddonPurchase);

    render(<MobileEventAddonSuccessPage />);

    await waitFor(() => {
      expect(purchaseMock).toHaveBeenCalledWith(fixtures.event.slug, {
        addonIntent: 'intent_abc',
        checkoutId: undefined,
        addonKey: undefined,
      });
    });

    expect(await screen.findByText('Purchase summary')).toBeInTheDocument();
    expect(screen.getByText('Sommerfest')).toBeInTheDocument();
    expect(screen.getByText('Extra photos 500')).toBeInTheDocument();
    expect(screen.getByText('ORDER-123')).toBeInTheDocument();
    expect(screen.getByText('TX-999')).toBeInTheDocument();
  });

  it('shows fallback error state when purchase is not found', async () => {
    vi.mocked(getEventAddonPurchase).mockResolvedValue(null as any);

    render(<MobileEventAddonSuccessPage />);

    expect(await screen.findByText('We are still confirming this purchase.')).toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'Open billing' }));
    expect(navigateMock).toHaveBeenCalledWith('/event-admin/mobile/billing');
  });
});
