import React from 'react';
import '@testing-library/jest-dom';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { ConfirmProvider } from './confirm';
import { PromptProvider } from './prompt';
import Attachments from './components/Attachments';
import { ToastProvider } from './toast';
import { I18nProvider } from './i18n/I18nProvider';
import { api } from './api';

jest.mock('./api', () => ({
  api: {
    get: jest.fn(),
    post: jest.fn(),
    patch: jest.fn(),
    delete: jest.fn(),
  },
}));

const mockedApi = api as jest.Mocked<typeof api>;

test('attachments empty state renders drag and drop guidance', async () => {
  mockedApi.get.mockResolvedValueOnce({ data: [] } as any);

  render(
    <ToastProvider>
      <I18nProvider>
        <ConfirmProvider>
          <PromptProvider>
            <Attachments jobId={42} />
          </PromptProvider>
        </ConfirmProvider>
      </I18nProvider>
    </ToastProvider>,
  );

  expect(await screen.findByText(/drag and drop files here/i)).toBeInTheDocument();
  expect(screen.getByText(/no attachments yet/i)).toBeInTheDocument();
  expect(screen.getByText(/max 10 mb each/i)).toBeInTheDocument();
});

test('attachments metadata controls update purpose and ai usage', async () => {
  mockedApi.get.mockResolvedValueOnce({
    data: [
      {
        id: 7,
        fileName: 'resume.pdf',
        uploadDate: new Date().toISOString(),
        fileType: 'application/pdf',
        fileSize: 2048,
        purpose: 'resume',
        useForAi: true,
      },
    ],
  } as any);
  mockedApi.patch.mockResolvedValue({ data: {} } as any);

  render(
    <ToastProvider>
      <I18nProvider>
        <ConfirmProvider>
          <PromptProvider>
            <Attachments jobId={42} />
          </PromptProvider>
        </ConfirmProvider>
      </I18nProvider>
    </ToastProvider>,
  );

  expect(await screen.findByDisplayValue(/resume/i)).toBeInTheDocument();
  expect(screen.getByRole('button', { name: 'Preview: resume.pdf' })).toBeInTheDocument();
  expect(screen.getByRole('button', { name: 'Download: resume.pdf' })).toBeInTheDocument();
  expect(screen.getByRole('button', { name: 'Rename: resume.pdf' })).toBeInTheDocument();
  expect(screen.getByRole('button', { name: 'Delete: resume.pdf' })).toBeInTheDocument();

  fireEvent.mouseDown(screen.getByRole('combobox'));
  fireEvent.click(await screen.findByRole('option', { name: /portfolio/i }));

  await waitFor(() => {
    expect(mockedApi.patch).toHaveBeenCalledWith('/attachments/7', expect.objectContaining({ purpose: 'portfolio', useForAi: true }));
  });

  fireEvent.click(screen.getByRole('switch'));

  await waitFor(() => {
    expect(mockedApi.patch).toHaveBeenCalledWith('/attachments/7', expect.objectContaining({ purpose: 'portfolio', useForAi: false }));
  });
});
