import { configure, fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import { describe, expect, it } from 'vitest';
import { FieldSelection } from './FieldSelection';

configure({ testIdAttribute: 'data-test-id' });

const MockField: React.FC<{ name: string; label: string }> = ({
  name,
  label,
}) => <div data-test-id={`field-${name}`}>{label}</div>;

describe('FieldSelection', () => {
  it('should render without crashing', () => {
    render(
      <FieldSelection>
        <MockField name="field1" label="Field 1" />
        <MockField name="field2" label="Field 2" />
      </FieldSelection>,
    );

    expect(screen.getByPlaceholderText('Select Field')).toBeInTheDocument();
  });

  it('should add a field to the selected fields when the add button is clicked', () => {
    render(
      <FieldSelection>
        <MockField name="field1" label="Field 1" />
        <MockField name="field2" label="Field 2" />
      </FieldSelection>,
    );

    fireEvent.change(screen.getByPlaceholderText('Select Field'), {
      target: { value: 'field1' },
    });
    fireEvent.click(screen.getByText('Field 1'));

    expect(screen.getByTestId('field-field1')).toBeInTheDocument();
  });

  it('should remove a field from the selected fields when the remove button is clicked', () => {
    render(
      <FieldSelection>
        <MockField name="field1" label="Field 1" />
        <MockField name="field2" label="Field 2" />
      </FieldSelection>,
    );

    fireEvent.change(screen.getByPlaceholderText('Select Field'), {
      target: { value: 'field1' },
    });
    fireEvent.click(screen.getByText('Field 1'));

    expect(screen.getByTestId('field-field1')).toBeInTheDocument();

    fireEvent.click(screen.getByTestId('remove-field-button'));

    expect(screen.queryByTestId('field-field1')).not.toBeInTheDocument();
  });
});
