import React from 'react';
import PropTypes from 'prop-types';
import { render as rtlRender, waitFor } from '@testing-library/react';
import { IntlProvider } from 'react-intl';
import { Router, Route } from 'react-router-dom';
import history from './history';
import { Provider } from 'react-redux';
import { configureStore } from '@capillarytech/vulcan-react-sdk/utils';
import { initialReducer } from '../initialReducer';

function Wrapper({ children }) {
  const store = configureStore({}, initialReducer, history);
  return (
    <Provider store={store}>
      <IntlProvider locale="en">{children}</IntlProvider>
    </Provider>
  );
}
Wrapper.propTypes = {
  children: PropTypes.array,
};

function render(ui, renderOptions = {}) {
  return rtlRender(ui, { wrapper: Wrapper, ...renderOptions });
}


function renderWithRouter(
  Component,
  props,
  { routePath = '/', historyPush = '/' } = {},
  renderOptions,
) {
  history.push(historyPush);

  return {
    history,
    ...rtlRender(
       <Router history={history}>
        <Route
        path={routePath}
          render={(routeProps) => <Component {...props} {...routeProps} />}
        />
      </Router>,
      { wrapper: Wrapper, ...renderOptions },
    ),
  };
}

// antd v6: the hidden a11y `[role=listbox]` only contains option `value`s, not
// labels. The visible, clickable options live in the portal under
// `.ant-select-dropdown` as `.ant-select-item-option` rows. The open dropdown
// is the one without the `ant-select-dropdown-hidden` modifier.
function getVisibleDropdown() {
  const dropdowns = Array.from(document.querySelectorAll('.ant-select-dropdown'))
    .filter((el) => !el.classList.contains('ant-select-dropdown-hidden'));
  return dropdowns[0];
}

async function findVisibleSelectOption(optionText, { timeout = 1000 } = {}) {
  return waitFor(() => {
    const dropdowns = Array.from(document.querySelectorAll('.ant-select-dropdown'))
      .filter((el) => !el.classList.contains('ant-select-dropdown-hidden'));
    for (const dd of dropdowns) {
      const items = Array.from(dd.querySelectorAll('.ant-select-item-option'));
      const match = items.find((it) => it.textContent === optionText);
      if (match) return match;
    }
    throw new Error(`Visible select option with text "${optionText}" not found`);
  }, { timeout });
}

// re-export everything
export * from '@testing-library/react';

// override render method
export {
  render,
  renderWithRouter,
  getVisibleDropdown,
  findVisibleSelectOption,
};
