import React from 'react';
import { render, screen, act, fireEvent } from '@testing-library/react';
import SourceList from './SourceList';

import { mockSource } from '../__mocks__/MockModels';

import GenericBrowserLib from '@squiz/generic-browser-lib'; // Import Functional Component
jest.mock('@squiz/generic-browser-lib', () => {
    return {
        ...jest.requireActual('@squiz/generic-browser-lib'),
    };
});

describe('SourceList', () => {
    it('should render <li> for each provided source', () => {
        const sources = [mockSource(), mockSource({ id: '2' })];
        const onSourceSelect = jest.fn();
        render(<SourceList sources={sources} onSourceSelect={onSourceSelect} />);

        expect(screen.getByLabelText('environment list')).toBeInTheDocument();
        expect(screen.getByLabelText('environment list').children.length).toEqual(2);
    });

    it('should render Icon based on source type', () => {
        jest.spyOn(GenericBrowserLib, 'Icon');
        const sources = [mockSource({ type: 'dam' })];
        const onSourceSelect = jest.fn();
        render(<SourceList sources={sources} onSourceSelect={onSourceSelect} />);
        expect(GenericBrowserLib.Icon).toHaveBeenCalledWith(expect.objectContaining({ icon: 'dam' }), {});
    });

    it('should render using source name', () => {
        const sources = [mockSource({ type: 'dam', name: 'mySource' })];
        const onSourceSelect = jest.fn();
        render(<SourceList sources={sources} onSourceSelect={onSourceSelect} />);
        expect(screen.getByText('mySource')).toBeInTheDocument();
    });

    it('should render using source id if name not provided', () => {
        const sources = [mockSource({ type: 'dam', name: undefined, id: '1115544' })];
        const onSourceSelect = jest.fn();
        render(<SourceList sources={sources} onSourceSelect={onSourceSelect} />);
        expect(screen.getByText('1115544')).toBeInTheDocument();
        expect(screen.queryByText('mySource')).not.toBeInTheDocument();
    });

    it('should call onSourceSelect with source object when clicked', async () => {
        const sources = [mockSource(), mockSource({ type: 'dam', name: 'mySource', id: '1115544' })];
        const onSourceSelect = jest.fn();
        render(<SourceList sources={sources} onSourceSelect={onSourceSelect} />);

        await act(() => fireEvent.click(screen.getByRole('button', { name: 'mySource' })));
        expect(onSourceSelect).toHaveBeenCalledWith(sources[1]);
    });
});
