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

const fixtures = vi.hoisted(() => ({
  event: {
    id: 1,
    name: 'Demo Event',
    slug: 'demo-event',
    event_date: '2026-02-12',
    event_type_id: 1,
    event_type: { id: 1, name: 'Wedding' },
    status: 'published',
    settings: {
      live_show: {
        moderation_mode: 'manual',
      },
    },
  },
}));

vi.mock('react-router-dom', () => ({
  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;
    },
    i18n: { language: 'en' },
  }),
}));

vi.mock('../../api', () => ({
  getEvent: vi.fn(),
  getLiveShowLink: vi.fn(),
  rotateLiveShowLink: vi.fn(),
  updateEvent: vi.fn(),
}));

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

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

vi.mock('../../lib/events', () => ({
  resolveEventDisplayName: () => fixtures.event.name,
}));

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

vi.mock('../components/MobileShell', () => ({
  MobileShell: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  HeaderActionButton: ({ children, onPress }: { children: React.ReactNode; onPress?: () => void }) => (
    <button type="button" onClick={onPress}>
      {children}
    </button>
  ),
}));

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>
  ),
  SkeletonCard: () => <div>Loading...</div>,
}));

vi.mock('../components/FormControls', () => ({
  MobileField: ({ label, children }: { label: string; children: React.ReactNode }) => (
    <label>
      {label}
      {children}
    </label>
  ),
  MobileInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
  MobileSelect: (props: React.SelectHTMLAttributes<HTMLSelectElement>) => <select {...props} />,
}));

vi.mock('../components/ContextHelpLink', () => ({
  ContextHelpLink: () => 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('@tamagui/react-native-web-lite', () => ({
  Pressable: ({
    children,
    onPress,
    disabled,
    ...rest
  }: {
    children: React.ReactNode;
    onPress?: () => void;
    disabled?: boolean;
    [key: string]: unknown;
  }) => (
    <button type="button" onClick={onPress} disabled={disabled} {...rest}>
      {children}
    </button>
  ),
}));

vi.mock('tamagui', () => ({
  Slider: Object.assign(
    ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
    {
      Track: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
      TrackActive: () => <div />,
      Thumb: () => <div />,
    }
  ),
}));

vi.mock('../theme', () => ({
  useAdminTheme: () => ({
    textStrong: '#111827',
    text: '#111827',
    muted: '#6b7280',
    danger: '#dc2626',
    border: '#e5e7eb',
    surface: '#ffffff',
    primary: '#ff5a5f',
  }),
}));

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

import MobileEventLiveShowSettingsPage from '../EventLiveShowSettingsPage';
import { getEvent, getLiveShowLink } from '../../api';

describe('MobileEventLiveShowSettingsPage', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.mocked(getEvent).mockResolvedValue(fixtures.event as any);
  });

  it('shows a validity timestamp when link expiry is present', async () => {
    vi.mocked(getLiveShowLink).mockResolvedValue({
      token: 'token-1',
      url: 'https://example.test/show/token-1',
      qr_code_data_url: null,
      rotated_at: null,
      expires_at: '2099-01-01T12:00:00Z',
    });

    render(<MobileEventLiveShowSettingsPage />);

    expect(await screen.findByText('Live Show link')).toBeInTheDocument();
    expect(await screen.findByText(/Valid until/)).toBeInTheDocument();
  });

  it('shows expired state and disables stale link actions', async () => {
    vi.mocked(getLiveShowLink).mockResolvedValue({
      token: 'token-2',
      url: 'https://example.test/show/token-2',
      qr_code_data_url: null,
      rotated_at: null,
      expires_at: '2000-01-01T00:00:00Z',
    });

    render(<MobileEventLiveShowSettingsPage />);

    expect(await screen.findByText(/Expired at/)).toBeInTheDocument();
    expect(screen.getByText('Rotate the link to generate a new active URL and QR code.')).toBeInTheDocument();

    expect(screen.getByRole('button', { name: 'Copy' })).toBeDisabled();
    expect(screen.getByRole('button', { name: 'Share' })).toBeDisabled();
    expect(screen.getByRole('button', { name: 'Open' })).toBeDisabled();
  });
});
