import { expect, test, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import DrugTable from '../src/components/Search/DrugTable';
import drugs from '../src/constants/mock_data';
import React from 'react';
import routes from '../src/constants/routes';
import { Provider } from 'react-redux';
import { store } from '../src/redux/store';
import axios from 'axios';

const mockedUseNavigate = vi.fn(() => {
  return (path: string) => {
    return routes[path];
  };
});
vi.mock('react-router-dom', async () => {
  const mod = await vi.importActual<typeof import('react-router-dom')>(
    'react-router-dom'
  );
  return {
    ...mod,
    useNavigate: () => mockedUseNavigate
  };
});

test('DrugTable renders correctly', () => {
  render(
    <Provider store={store}>
      <DrugTable />
    </Provider>
  );
  vi.spyOn(axios, 'get').mockResolvedValue({
    data: { Page: 1, PageSize: 10, Total: 16, Items: drugs }
  });
  expect(screen.getByText('Name')).toBeTruthy();
  expect(screen.getByText('Price (USD)')).toBeTruthy();
  expect(screen.getByText('Manufacturer')).toBeTruthy();
});

test('DrugTable renders correct number of rows', async () => {
  vi.spyOn(axios, 'get').mockResolvedValue({
    data: { Page: 1, PageSize: 10, total: 16, items: drugs.slice(0, 10) }
  });
  render(
    <Provider store={store}>
      <DrugTable />
    </Provider>
  );
  await new Promise((r) => setTimeout(r, 1000));
  // Header row + 10 data rows + 1 row for pagination
  expect(screen.getAllByRole('row')).toHaveLength(12);
  vi.spyOn(axios, 'get').mockResolvedValue({
    data: { Page: 2, PageSize: 10, total: 16, items: drugs.slice(9, 16) }
  });
  fireEvent.click(screen.getByLabelText('next page'));
  // Header row + 6 data rows + 1 empty row to keep style + 1 row for pagination
  await new Promise((r) => setTimeout(r, 1000));
  expect(screen.getAllByRole('row')).toHaveLength(9);
});

test('DrugTable buttons work correctly', async () => {
  vi.spyOn(axios, 'get').mockResolvedValue({
    data: { Page: 1, PageSize: 10, total: 16, items: drugs.slice(0, 10) }
  });
  render(
    <Provider store={store}>
      <DrugTable />
    </Provider>
  );
  await new Promise((r) => setTimeout(r, 1000));
  fireEvent.click(screen.getAllByText('View').pop()!);
  expect(mockedUseNavigate).toHaveBeenCalledWith('/details/10');
  fireEvent.click(screen.getAllByText('Update').pop()!);
  expect(mockedUseNavigate).toHaveBeenCalledWith('/update/10');
  fireEvent.click(screen.getAllByText('Delete').pop()!);
  expect(mockedUseNavigate).toHaveBeenCalledWith('/update/10');
});
