import { jest } from '@jest/globals';
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import CheckboxInput from '../pages/GlobalConfig/Inputs/CheckboxInput.js';

describe('CheckboxInput Component', () => {
  const mockOnChange = jest.fn();
  
  const defaultField = {
    ProKey: 'testKey',
    ProValue: 'false',
    Label: 'Test Checkbox',
  };

  beforeEach(() => {
    mockOnChange.mockClear();
  });

  it('renders the checkbox with label', () => {
    render(<CheckboxInput field={defaultField} onChange={mockOnChange} />);
    expect(screen.getByText('Test Checkbox')).toBeInTheDocument();
  });

  it('renders unchecked when ProValue is "false"', () => {
    render(<CheckboxInput field={defaultField} onChange={mockOnChange} />);
    const checkbox = screen.getByRole('checkbox');
    expect(checkbox).not.toBeChecked();
  });

  it('renders checked when ProValue is "true"', () => {
    const checkedField = { ...defaultField, ProValue: 'true' };
    render(<CheckboxInput field={checkedField} onChange={mockOnChange} />);
    const checkbox = screen.getByRole('checkbox');
    expect(checkbox).toBeChecked();
  });

  it('calls onChange when checkbox is clicked', () => {
    render(<CheckboxInput field={defaultField} onChange={mockOnChange} />);
    const checkbox = screen.getByRole('checkbox');
    fireEvent.click(checkbox);
    expect(mockOnChange).toHaveBeenCalledWith(true);
  });

  it('renders disabled checkbox when disabled prop is true', () => {
    render(<CheckboxInput field={defaultField} onChange={mockOnChange} disabled={true} />);
    const checkbox = screen.getByRole('checkbox');
    expect(checkbox).toBeDisabled();
  });

  it('displays error message when field has Error', () => {
    const fieldWithError = { ...defaultField, Error: 'This field is required' };
    render(<CheckboxInput field={fieldWithError} onChange={mockOnChange} />);
    expect(screen.getByText('This field is required')).toBeInTheDocument();
  });

  it('does not display error when field has no Error', () => {
    render(<CheckboxInput field={defaultField} onChange={mockOnChange} />);
    expect(screen.queryByText(/required/i)).not.toBeInTheDocument();
  });

  it('has correct name attribute on checkbox', () => {
    render(<CheckboxInput field={defaultField} onChange={mockOnChange} />);
    const checkbox = screen.getByRole('checkbox');
    expect(checkbox).toHaveAttribute('name', 'testKey');
  });
});
