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

const navigateMock = vi.fn();
const uploadPhotoMock = vi.fn();
const addToQueueMock = vi.fn();

vi.mock('react-router-dom', () => ({
  useNavigate: () => navigateMock,
  useSearchParams: () => [new URLSearchParams('taskId=12')],
}));

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/button', () => ({
  Button: ({ children, onPress, ...rest }: { children: React.ReactNode; onPress?: () => void }) => (
    <button type="button" onClick={onPress} {...rest}>
      {children}
    </button>
  ),
}));

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

vi.mock('../services/uploadApi', () => ({
  uploadPhoto: (...args: unknown[]) => uploadPhotoMock(...args),
  useUploadQueue: () => ({ items: [], add: addToQueueMock }),
}));

vi.mock('../services/tasksApi', () => ({
  fetchTasks: vi.fn().mockResolvedValue([{ id: 12, title: 'Capture the dancefloor', description: 'Find the happiest crew.' }]),
}));

vi.mock('@/shared/guest/services/pendingUploadsApi', () => ({
  fetchPendingUploadsSummary: vi.fn().mockResolvedValue({ items: [], totalCount: 0 }),
}));

vi.mock('../context/GuestIdentityContext', () => ({
  useOptionalGuestIdentity: () => ({ name: 'Alex' }),
}));

vi.mock('@/shared/guest/hooks/useGuestTaskProgress', () => ({
  useGuestTaskProgress: () => ({ markCompleted: vi.fn() }),
}));

vi.mock('@/shared/guest/i18n/useTranslation', () => ({
  useTranslation: () => ({
    t: (_key: string, arg2?: Record<string, string | number> | string, arg3?: string) =>
      typeof arg2 === 'string' || arg2 === undefined ? (arg2 ?? arg3 ?? _key) : (arg3 ?? _key),
    locale: 'en',
  }),
}));

vi.mock('@/hooks/use-appearance', () => ({
  useAppearance: () => ({ resolved: 'light' }),
}));

import UploadScreen from '../screens/UploadScreen';

Object.defineProperty(URL, 'createObjectURL', {
  writable: true,
  value: vi.fn(() => 'blob:preview'),
});
Object.defineProperty(URL, 'revokeObjectURL', {
  writable: true,
  value: vi.fn(),
});

describe('UploadScreen', () => {
  beforeEach(() => {
    navigateMock.mockReset();
    uploadPhotoMock.mockReset();
    addToQueueMock.mockReset();
  });

  it('renders queue entry point', () => {
    render(
      <EventDataProvider token="token">
        <UploadScreen />
      </EventDataProvider>
    );

    expect(screen.getByText('Queue')).toBeInTheDocument();
  });

  it('renders task summary when taskId is present', async () => {
    render(
      <EventDataProvider token="token">
        <UploadScreen />
      </EventDataProvider>
    );

    expect(await screen.findByText('Capture the dancefloor')).toBeInTheDocument();
  });

  it('redirects to queue with notice when upload fails because of network', async () => {
    uploadPhotoMock.mockRejectedValueOnce({ code: 'network_error' });
    addToQueueMock.mockResolvedValueOnce(undefined);

    const { container } = render(
      <EventDataProvider token="token">
        <UploadScreen />
      </EventDataProvider>
    );

    const input = container.querySelector('input[type="file"]') as HTMLInputElement;
    const file = new File(['demo'], 'demo.jpg', { type: 'image/jpeg' });

    fireEvent.change(input, { target: { files: [file] } });
    fireEvent.click(await screen.findByText('Foto verwenden'));

    await waitFor(() => {
      expect(addToQueueMock).toHaveBeenCalled();
      expect(navigateMock).toHaveBeenCalledWith('../queue?notice=network-retry');
    });
  });

  it('uploads all selected photos when multiple files are picked', async () => {
    uploadPhotoMock.mockResolvedValueOnce(101).mockResolvedValueOnce(102);

    const { container } = render(
      <EventDataProvider token="token">
        <UploadScreen />
      </EventDataProvider>
    );

    const input = container.querySelector('input[type="file"]') as HTMLInputElement;
    const first = new File(['one'], 'one.jpg', { type: 'image/jpeg' });
    const second = new File(['two'], 'two.jpg', { type: 'image/jpeg' });

    fireEvent.change(input, { target: { files: [first, second] } });
    fireEvent.click(await screen.findByText('Upload {count} photos'));

    await waitFor(() => {
      expect(uploadPhotoMock).toHaveBeenCalledTimes(2);
    });
    expect(addToQueueMock).not.toHaveBeenCalled();
  });

  it('accepts image files with empty mime type when extension is valid', async () => {
    const { container } = render(
      <EventDataProvider token="token">
        <UploadScreen />
      </EventDataProvider>
    );

    const input = container.querySelector('input[type="file"]') as HTMLInputElement;
    const file = new File(['rawdata'], 'from-library.jpg', { type: '' });

    fireEvent.change(input, { target: { files: [file] } });

    expect(await screen.findByLabelText('Remove photo')).toBeInTheDocument();
    expect(screen.getByText('{count} photos selected')).toBeInTheDocument();
  });
});
