import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import * as api from '../../api';

const fixtures = vi.hoisted(() => ({
  event: {
    id: 1,
    name: 'Demo Event',
    slug: 'demo-event',
    event_date: '2026-02-19',
    event_type_id: null,
    event_type: {
      id: 1,
      slug: 'wedding',
      name: 'Wedding',
      name_translations: { de: 'Hochzeit', en: 'Wedding' },
      icon: null,
      settings: {},
      created_at: null,
      updated_at: null,
    },
    status: 'published',
    settings: {},
  },
  assignedTasks: [
    { id: 1, title: 'Task A', description: 'Desc', emotion: null, event_type_id: null },
    { id: 2, title: 'Task B', description: '', emotion: null, event_type_id: null },
  ],
  libraryTasks: [
    { id: 3, title: 'Task C', description: '', emotion: null, event_type_id: null },
  ],
  collections: [{ id: 1, name: 'Starter Pack', description: '' }],
  emotions: [{ id: 1, name: 'Joy', color: '#ff6b6b' }],
}));

const navigateMock = vi.fn();
const backMock = vi.fn();

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

const tMock = (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-i18next', () => ({
  useTranslation: () => ({
    t: tMock,
  }),
}));

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

const selectEventMock = vi.fn();

vi.mock('../../context/EventContext', () => ({
  useEventContext: () => ({
    activeEvent: fixtures.event,
    selectEvent: selectEventMock,
  }),
}));

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

vi.mock('../../api', () => ({
  getEvent: vi.fn().mockResolvedValue(fixtures.event),
  getEvents: vi.fn().mockResolvedValue([fixtures.event]),
  getEventTasks: vi.fn().mockResolvedValue({ data: fixtures.assignedTasks }),
  getTasks: vi.fn().mockResolvedValue({ data: fixtures.libraryTasks }),
  getTaskCollections: vi.fn().mockResolvedValue({ data: fixtures.collections }),
  getEmotions: vi.fn().mockResolvedValue(fixtures.emotions),
  assignTasksToEvent: vi.fn(),
  updateEvent: vi.fn().mockResolvedValue(fixtures.event),
  updateTask: vi.fn(),
  importTaskCollection: vi.fn(),
  createTask: vi.fn(),
  detachTasksFromEvent: vi.fn(),
  createEmotion: vi.fn(),
  updateEmotion: vi.fn(),
  deleteEmotion: vi.fn(),
}));

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

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

vi.mock('@tamagui/scroll-view', () => ({
  ScrollView: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));

vi.mock('tamagui', () => ({
  Tabs: Object.assign(({ children }: { children: React.ReactNode }) => <div>{children}</div>, {
    List: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
    Tab: ({ children }: { children: React.ReactNode }) => <button type="button">{children}</button>,
  }),
}));

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

vi.mock('@tamagui/list-item', () => ({
  ListItem: ({
    title,
    subTitle,
    iconAfter,
    ...rest
  }: {
    title?: React.ReactNode;
    subTitle?: React.ReactNode;
    iconAfter?: React.ReactNode;
  }) => (
    <div {...rest}>
      {title}
      {subTitle}
      {iconAfter}
    </div>
  ),
}));

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

vi.mock('@tamagui/button', () => ({
  Button: ({ children, onPress }: { children: React.ReactNode; onPress?: () => void }) => (
    <button type="button" onClick={onPress}>
      {children}
    </button>
  ),
}));

vi.mock('@tamagui/checkbox', () => ({
  Checkbox: Object.assign(
    ({ children, checked, onCheckedChange, 'aria-label': ariaLabel }: any) => (
      <button
        type="button"
        aria-label={ariaLabel}
        aria-pressed={checked}
        onClick={() => onCheckedChange?.(!checked)}
      >
        {children}
      </button>
    ),
    { Indicator: ({ children }: { children: React.ReactNode }) => <span>{children}</span> },
  ),
}));

vi.mock('@tamagui/radio-group', () => ({
  RadioGroup: Object.assign(({ children }: { children: React.ReactNode }) => <div>{children}</div>, {
    Item: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
    Indicator: () => <div />,
  }),
}));

vi.mock('@tamagui/alert-dialog', () => ({
  AlertDialog: Object.assign(({ children }: { children: React.ReactNode }) => <div>{children}</div>, {
    Portal: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
    Overlay: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,
    Content: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
    Title: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
    Description: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
    Cancel: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
    Action: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  }),
}));

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>,
  PillBadge: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  CTAButton: ({ label, onPress }: { label: string; onPress?: () => void }) => (
    <button type="button" onClick={onPress}>
      {label}
    </button>
  ),
  SkeletonCard: () => <div>Loading...</div>,
  FloatingActionButton: ({ label }: { label: string }) => <div>{label}</div>,
}));

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

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

vi.mock('../components/Tag', () => ({
  Tag: ({ label }: { label: string }) => <span>{label}</span>,
}));

vi.mock('../theme', () => ({
  ADMIN_ACTION_COLORS: {
    settings: '#0ea5e9',
    tasks: '#f59e0b',
    qr: '#6366f1',
    branding: '#22c55e',
  },
  useAdminTheme: () => ({
    textStrong: '#111827',
    muted: '#6b7280',
    subtle: '#94a3b8',
    border: '#e5e7eb',
    primary: '#ff5a5f',
    danger: '#dc2626',
    surface: '#ffffff',
    surfaceMuted: '#f9fafb',
    dangerBg: '#fee2e2',
    dangerText: '#b91c1c',
    overlay: 'rgba(15,23,42,0.5)',
    shadow: 'rgba(15,23,42,0.12)',
  }),
}));

import MobileEventTasksPage from '../EventTasksPage';

describe('MobileEventTasksPage', () => {
  it('renders the quick jump chips and photo task header', async () => {
    render(<MobileEventTasksPage />);

    expect(await screen.findByText('Photo task mode')).toBeInTheDocument();
    expect(screen.getByText('Quick jump')).toBeInTheDocument();
    expect(screen.getByText('assigned')).toBeInTheDocument();
    expect(screen.getByPlaceholderText('Search photo tasks')).toBeInTheDocument();
    expect(screen.getByText('Emotion')).toBeInTheDocument();

    expect(api.getTaskCollections).toHaveBeenCalledWith(
      expect.objectContaining({ event_type: 'wedding' }),
    );
  });

  it('toggles task details in the hero section', async () => {
    render(<MobileEventTasksPage />);

    const detailsLabel = 'Control whether guests see mission cards and prompts.';
    expect(await screen.findByText('Photo task mode')).toBeInTheDocument();
    expect(screen.queryByText(detailsLabel)).not.toBeInTheDocument();

    fireEvent.click(screen.getByLabelText(detailsLabel));
    expect(screen.getByText(detailsLabel)).toBeInTheDocument();
  });

  it('enters selection mode on long press', async () => {
    render(<MobileEventTasksPage />);

    const task = await screen.findByText('Task A');
    await act(async () => {
      fireEvent.pointerDown(task);
      await new Promise((resolve) => setTimeout(resolve, 500));
      fireEvent.pointerUp(task);
    });

    expect((await screen.findAllByText('Auswahl löschen')).length).toBeGreaterThan(0);
  });

  it('hides the add FAB when the task limit is reached', async () => {
    (api.getEvent as unknown as { mockResolvedValueOnce: (value: any) => void }).mockResolvedValueOnce({
      ...fixtures.event,
      limits: {
        tasks: {
          limit: 2,
          remaining: 0,
        },
      },
    });

    render(<MobileEventTasksPage />);

    expect(await screen.findByText('Photo task mode')).toBeInTheDocument();
    await waitFor(() => {
      expect(screen.queryByLabelText('Add')).not.toBeInTheDocument();
    });
  });
});
