import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import CustomTextField from './CustomTextField';

const renderField = (props: Partial<React.ComponentProps<typeof CustomTextField>> = {}) => {
  const changeHandler = props.changeHandler ?? jest.fn();
  render(
    <ThemeProvider theme={createTheme()}>
      <CustomTextField
        label={props.label ?? 'Username'}
        name={props.name ?? 'username'}
        changeHandler={changeHandler}
        isMultline={props.isMultline ?? false}
      />
    </ThemeProvider>
  );
  return { changeHandler };
};

describe('CustomTextField', () => {
  it('renders labeled text input', () => {
    renderField({ label: 'Email', name: 'email' });
    expect(screen.getByLabelText('Email')).toBeInTheDocument();
  });

  it('calls changeHandler when user types', async () => {
    const user = userEvent.setup();
    const { changeHandler } = renderField();

    await user.type(screen.getByLabelText('Username'), 'abc');
    expect(changeHandler).toHaveBeenCalled();
  });

  it('supports multiline mode', () => {
    renderField({ label: 'Notes', name: 'notes', isMultline: true });
    expect(screen.getByLabelText('Notes').tagName).toBe('TEXTAREA');
  });
});
