import { render, screen, mockMatchMedia } from '../test-utils';
import { userEvent } from '@testing-library/user-event';
import '@testing-library/jest-dom';
import Table, { TableProps } from './Table';

mockMatchMedia();

describe('Table Component', () => {
  const defaultProps: TableProps = {
    data: {
      headers: [{ header: 'Header 1' }, { header: 'Header 2' }],
      rows: [
        {
          cells: [
            { cell: { type: 'text', text: 'Cell content 1' } },
            { cell: { type: 'text', text: 'Cell content 2' } },
          ],
        },
        {
          cells: [
            { cell: { type: 'text', text: 'Cell content 3' } },
            { cell: { type: 'text', text: 'Cell content 4' } },
          ],
        },
      ],
      onRowClick: jest.fn(),
    },
    loading: false,
    className: '',
    fullWidth: true,
    error: undefined,
  };

  it('renders table', () => {
    render(<Table {...defaultProps} />);
    expect(screen.getByText('Header 1')).toBeInTheDocument();
    expect(screen.getByText('Header 2')).toBeInTheDocument();
    expect(screen.getByText('Cell content 1')).toBeInTheDocument();
    expect(screen.getByText('Cell content 2')).toBeInTheDocument();
    expect(screen.getByText('Cell content 3')).toBeInTheDocument();
    expect(screen.getByText('Cell content 4')).toBeInTheDocument();
  });

  it('renders `loading` state on loading', () => {
    render(<Table {...defaultProps} loading />);
    expect(screen.getAllByTestId('np-table-loader')).toHaveLength(1);
  });

  it('renders `empty data` message for empty table`s data', () => {
    render(<Table {...defaultProps} data={{ headers: [], rows: [] }} />);
    expect(screen.getAllByTestId('np-table-empty-data')).toHaveLength(1);
  });

  it('renders `error` message if `error` is passed', () => {
    const errorProps: TableProps = {
      ...defaultProps,
      error: { message: 'Error occurred', action: { text: 'Retry' } },
    };
    render(<Table {...errorProps} />);
    expect(screen.getByText('Error occurred')).toBeInTheDocument();
    expect(screen.getByText('Retry')).toBeInTheDocument();
  });

  it('renders with custom class name', () => {
    render(<Table {...defaultProps} className="custom-class" />);
    expect(screen.getByTestId('np-table-outer-container')).toHaveClass('custom-class');
  });

  it('renders with `fullWidth` set to false', () => {
    render(<Table {...defaultProps} fullWidth={false} />);
    expect(screen.getByTestId('np-table-outer-container')).toHaveClass(
      'np-table-outer-container--center',
    );
  });

  it('calls `onRowClick` when a row is clicked', async () => {
    render(<Table {...defaultProps} />);
    await userEvent.click(screen.getByText('Cell content 1'));
    expect(defaultProps.data.onRowClick).toHaveBeenCalled();
  });
});
