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: 42,
    name: { de: 'Demo Event DE', en: 'Demo Event EN' },
    slug: 'demo-event',
    status: 'published',
    event_date: '2026-02-01T12:00:00Z',
    settings: {},
    package: {
      id: 10,
      name: 'Premium',
      expires_at: '2026-03-01T00:00:00Z',
    },
    limits: null,
  },
  catalog: [
    {
      key: 'extend_gallery_30d',
      label: 'Extend gallery 30 days',
      price_id: 'paypal',
      increments: { extra_gallery_days: 30 },
      price: 4,
      currency: 'EUR',
    },
    {
      key: 'extra_photos_500',
      label: 'Extra photos 500',
      price_id: 'paypal',
      increments: { extra_photos: 500 },
      price: 5,
      currency: 'EUR',
    },
  ],
  history: [
    {
      id: 501,
      addon_key: 'extend_gallery_30d',
      label: 'Extend gallery 30 days',
      amount: 4,
      currency: 'EUR',
      status: 'completed',
      purchased_at: '2026-01-22T10:00:00Z',
      extra_photos: 0,
      extra_guests: 0,
      extra_gallery_days: 30,
      quantity: 1,
      event: { id: 42, slug: 'demo-event', name: 'Demo Event' },
    },
  ],
}));

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

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('../theme', () => ({
  useAdminTheme: () => ({
    text: '#111827',
    muted: '#6b7280',
    subtle: '#94a3b8',
    border: '#e5e7eb',
    primary: '#2563eb',
    successText: '#16a34a',
    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('../components/LegalConsentSheet', () => ({
  LegalConsentSheet: ({
    open,
    onConfirm,
  }: {
    open: boolean;
    onConfirm: (consents: { acceptedTerms: boolean; acceptedWaiver: boolean }) => void;
  }) => (open ? <button type="button" onClick={() => onConfirm({ acceptedTerms: true, acceptedWaiver: true })}>Confirm legal</button> : null),
}));

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('react-hot-toast', () => ({
  default: {
    success: vi.fn(),
    error: vi.fn(),
  },
}));

vi.mock('../../api', () => ({
  getEvent: vi.fn().mockResolvedValue(fixtures.event),
  getAddonCatalog: vi.fn().mockResolvedValue(fixtures.catalog),
  getTenantAddonHistory: vi.fn().mockResolvedValue({ data: fixtures.history }),
  createEventAddonCheckout: vi.fn().mockResolvedValue({
    checkout_url: null,
    checkout_id: 'chk_123',
    expires_at: null,
  }),
}));

import MobileEventAddonsPage from '../EventAddonsPage';
import { createEventAddonCheckout } from '../../api';

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

  it('renders add-ons and event-specific purchase history', async () => {
    render(<MobileEventAddonsPage />);

    expect(await screen.findByText('Demo Event DE')).toBeInTheDocument();
    expect((await screen.findAllByText('Extend gallery 30 days')).length).toBeGreaterThan(0);
    expect(screen.getByText('Extra photos 500')).toBeInTheDocument();
    expect(screen.getByText('Purchased add-ons for this event')).toBeInTheDocument();
  });

  it('requires legal consent and sends checkout payload', async () => {
    const checkoutMock = vi.mocked(createEventAddonCheckout);

    render(<MobileEventAddonsPage />);

    const buyButtons = await screen.findAllByRole('button', { name: 'Buy add-on' });
    fireEvent.click(buyButtons[0]);

    expect(checkoutMock).not.toHaveBeenCalled();

    fireEvent.click(await screen.findByRole('button', { name: 'Confirm legal' }));

    await waitFor(() => {
      expect(checkoutMock).toHaveBeenCalledWith(fixtures.event.slug, {
        addon_key: 'extra_photos_500',
        success_url: `${window.location.origin}/event-admin/mobile/events/demo-event/addons/success?addon_key=extra_photos_500`,
        cancel_url: `${window.location.origin}/event-admin/mobile/events/demo-event/addons`,
        accepted_terms: true,
        accepted_waiver: true,
      });
    });
  });
});
