import React, { useState } from 'react';
import {
  render, screen,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom';
import { IntlProvider } from 'react-intl';
import DynamicControlsStep from '../DynamicControlsStep';

const SAMPLE_CONTROLS = [
  { key: 'alpha', label: 'Alpha', description: 'Alpha help' },
  { key: 'beta', label: 'Beta', description: 'Beta help' },
];

function renderWithIntl(ui) {
  return render(
    <IntlProvider locale="en" messages={{}} defaultLocale="en">
      {ui}
    </IntlProvider>,
  );
}

function DynamicControlsHarness({ initialDynamicControls = {} }) {
  const [value, setValue] = useState({ dynamicControls: initialDynamicControls });
  return (
    <DynamicControlsStep
      value={value}
      onChange={setValue}
      controls={SAMPLE_CONTROLS}
    />
  );
}

describe('DynamicControlsStep', () => {
  it('renders nothing when there are no controls', () => {
    const { container } = renderWithIntl(
      <DynamicControlsStep
        value={{}}
        onChange={jest.fn()}
        controls={[]}
      />,
    );
    expect(container.firstChild).toBeNull();
  });

  it('shows each switch on (true) or off (false) from dynamicControls for every field', () => {
    renderWithIntl(
      <DynamicControlsHarness initialDynamicControls={{ alpha: true, beta: false }} />,
    );

    expect(screen.getByText('Other controls')).toBeInTheDocument();
    expect(screen.getByText('Alpha')).toBeInTheDocument();
    expect(screen.getByText('Beta')).toBeInTheDocument();

    const switches = screen.getAllByRole('switch');
    expect(switches).toHaveLength(2);
    expect(switches[0]).toBeChecked();
    expect(switches[1]).not.toBeChecked();
  });

  it('toggles every control through false and true via onChange', async () => {
    renderWithIntl(
      <DynamicControlsHarness initialDynamicControls={{ alpha: true, beta: false }} />,
    );
    const switches = screen.getAllByRole('switch');

    await userEvent.click(switches[0]);
    expect(switches[0]).not.toBeChecked();

    await userEvent.click(switches[1]);
    expect(switches[1]).toBeChecked();

    await userEvent.click(switches[0]);
    expect(switches[0]).toBeChecked();

    await userEvent.click(switches[1]);
    expect(switches[1]).not.toBeChecked();
  });

  it('renders validation error when error is set', () => {
    renderWithIntl(
      <DynamicControlsStep
        value={{ dynamicControls: { alpha: false } }}
        onChange={jest.fn()}
        controls={[SAMPLE_CONTROLS[0]]}
        error="Dynamic controls validation failed"
      />,
    );
    expect(screen.getByText('Dynamic controls validation failed')).toBeInTheDocument();
  });
});
