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

const backMock = vi.fn();
const navigateMock = vi.fn();
const selectEventMock = vi.fn();
const refetchMock = vi.fn();
const invalidateQueriesMock = vi.fn();
const paramsState: { slug?: string } = {};

vi.mock('react-router-dom', () => ({
  useNavigate: () => navigateMock,
  useParams: () => paramsState,
}));

vi.mock('@tanstack/react-query', () => ({
  useQueryClient: () => ({
    invalidateQueries: invalidateQueriesMock,
  }),
}));

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

vi.mock('../../api', () => ({
  createEvent: vi.fn(),
  getEvent: vi.fn(),
  updateEvent: vi.fn(),
  getEventTypes: vi.fn().mockResolvedValue([]),
  getPackages: vi.fn().mockResolvedValue([]),
  trackOnboarding: vi.fn(),
}));

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

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>
  ),
  FloatingActionButton: ({ label, onPress }: { label: string; onPress?: () => void }) => (
    <button type="button" onClick={onPress}>
      {label}
    </button>
  ),
}));

vi.mock('../components/FormControls', () => ({
  MobileField: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  MobileDateTimeInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => (
    <input type="datetime-local" {...props} />
  ),
  MobileInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
  MobileSelect: ({ children, ...props }: { children: React.ReactNode }) => <select {...props}>{children}</select>,
  MobileTextArea: (props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) => <textarea {...props} />,
}));

vi.mock('../components/LegalConsentSheet', () => ({
  LegalConsentSheet: () => 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/switch', () => ({
  Switch: Object.assign(
    ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
    { Thumb: () => <div /> },
  ),
}));

vi.mock('../theme', () => ({
  useAdminTheme: () => ({
    text: '#111827',
    muted: '#6b7280',
    subtle: '#94a3b8',
    danger: '#b91c1c',
    border: '#e5e7eb',
    surface: '#ffffff',
    primary: '#ff5a5f',
    glassSurface: 'rgba(255,255,255,0.8)',
    glassSurfaceStrong: 'rgba(255,255,255,0.9)',
    glassBorder: 'rgba(229,231,235,0.7)',
    glassShadow: 'rgba(15,23,42,0.14)',
    appBackground: 'linear-gradient(180deg, #f7fafc, #eef3f7)',
  }),
}));

vi.mock('../../auth/context', () => ({
  useAuth: () => ({ user: { role: 'tenant_admin' } }),
}));

vi.mock('../../context/EventContext', () => ({
  useEventContext: () => ({
    selectEvent: selectEventMock,
    refetch: refetchMock,
  }),
}));

import { getEvent, getEventTypes } from '../../api';
import MobileEventFormPage from '../EventFormPage';

describe('MobileEventFormPage', () => {
  afterEach(() => {
    paramsState.slug = undefined;
  });

  it('renders a save draft button when creating a new event', async () => {
    paramsState.slug = undefined;
    await act(async () => {
      render(<MobileEventFormPage />);
    });

    const saveDraft = screen.getByText('eventForm.actions.saveDraft');
    fireEvent.click(saveDraft);

    expect(backMock).toHaveBeenCalled();
  });

  it('defaults event type to wedding when available', async () => {
    paramsState.slug = undefined;
    vi.mocked(getEventTypes).mockResolvedValueOnce([
      { id: 11, slug: 'conference', name: 'Conference', name_translations: {}, icon: null, settings: {} },
      { id: 22, slug: 'wedding', name: 'Wedding', name_translations: {}, icon: null, settings: {} },
    ]);

    await act(async () => {
      render(<MobileEventFormPage />);
    });

    const select = screen.getByRole('combobox');
    expect(select).toHaveValue('22');
  });

  it('disables the date field when the event is completed', async () => {
    paramsState.slug = 'past-event';
    vi.mocked(getEvent).mockResolvedValueOnce({
      id: 1,
      name: 'Past event',
      slug: 'past-event',
      event_date: '2020-01-01T10:00:00Z',
      event_type_id: null,
      event_type: null,
      status: 'archived',
      description: null,
      settings: {},
    } as any);

    render(<MobileEventFormPage />);

    const dateInput = await screen.findByDisplayValue('2020-01-01T10:00');
    expect(dateInput).toBeDisabled();
  });
});
