import React from 'react';
import userEvent from '@testing-library/user-event';
import { renderInAppContext } from '@theorchard/suite-testing';
import MatchesTable, { CLASS_NAME } from '../matchesTable';

describe('<MatchesTable />', () => {
    const mockTrackMetadata = {
        trackName: 'Test Track',
        label: 'Test Label',
        imprint: 'Test Imprint',
        artists: ['Test Artist'],
    };

    const mockTableData = [
        {
            trackName: 'Test Track 1',
            distributorName: 'Test Distributor 1',
            trackNumber: 1,
            artistName: ['Test Artist 1'],
            oaTrackLink: 'https://example.com/track/1',
            accountId: '12345',
            imprintName: 'Test Label 1',
            matchType: 'internal',
            upc: '123456789012',
        },
        {
            trackName: 'Test Track 2',
            distributorName: 'Test Distributor 2',
            trackNumber: 2,
            artistName: ['Test Artist 2'],
            songwhipLinks: {
                spotify: [{ link: 'https://spotify.com/track/1' }],
                appleMusic: [{ link: 'https://apple.com/track/1' }],
            },
            accountId: null,
            imprintName: 'Test Label 2',
            matchType: 'external',
        },
    ];

    test('matches snapshot', () => {
        const component = renderInAppContext(
            <MatchesTable
                trackMetadata={mockTrackMetadata}
                trackDataLoading={false}
                tableData={[]}
            />
        );
        expect(component).toMatchSnapshot();
    });

    test('track metadata is displayed correctly', () => {
        const { container, getByText } = renderInAppContext(
            <MatchesTable
                trackMetadata={mockTrackMetadata}
                trackDataLoading={false}
                tableData={mockTableData}
            />
        );
        const headerLabels =
            container
                .querySelector(
                    '.PotentialAudioInfringementModal-MatchesTable-header'
                )
                ?.querySelectorAll('.form-label') ?? [];
        expect(headerLabels[0]).toHaveTextContent('Track Name');
        expect(headerLabels[1]).toHaveTextContent('Artist Name');
        expect(headerLabels[2]).toHaveTextContent('Account Name');

        expect(getByText('Test Track')).toBeVisible();
        expect(getByText('Test Label')).toBeVisible();
        expect(getByText('Test Artist')).toBeVisible();

        expect(getByText('Submitted Track Info')).toBeVisible();
        expect(getByText('Matched Audio Info')).toBeVisible();
    });

    test('displays CrossAccountOSRConflictMatches correctly', () => {
        const { getByText } = renderInAppContext(
            <MatchesTable
                trackMetadata={mockTrackMetadata}
                trackDataLoading={false}
                tableData={[mockTableData[0]]}
            />
        );

        expect(getByText('Test Track 1')).toBeVisible();
        expect(getByText('Test Artist 1')).toBeVisible();
        expect(getByText('Test Label 1')).toBeVisible();
        expect(getByText('Account ID: 12345')).toBeVisible();
        expect(getByText('Test Distributor 1')).toBeVisible();
    });

    test('displays PotentialAudioInfringementMatches correctly', () => {
        const { getByText } = renderInAppContext(
            <MatchesTable
                trackMetadata={mockTrackMetadata}
                trackDataLoading={false}
                tableData={[mockTableData[1]]}
            />
        );

        expect(getByText('Test Track 2')).toBeVisible();
        expect(getByText('Test Artist 2')).toBeVisible();
        expect(getByText('Test Label 2')).toBeVisible();
        expect(getByText('Test Distributor 2')).toBeVisible();
    });

    test('displays loading state', () => {
        const { getByTestId } = renderInAppContext(
            <MatchesTable
                trackMetadata={mockTrackMetadata}
                trackDataLoading={true}
                tableData={[]}
            />
        );

        const gridTable = getByTestId('GridTable');
        expect(gridTable).toHaveClass('loading');
    });

    test('handles empty matches gracefully', () => {
        const { getByText } = renderInAppContext(
            <MatchesTable
                trackMetadata={mockTrackMetadata}
                trackDataLoading={false}
                tableData={[]}
            />
        );

        expect(getByText('data_empty')).toBeVisible();
    });

    test('handle expand/shrink state of the rows correctly', () => {
        const { getByText, queryByText } = renderInAppContext(
            <MatchesTable
                trackMetadata={mockTrackMetadata}
                trackDataLoading={false}
                tableData={mockTableData}
            />
        );

        const expandableRow = getByText('Test Track 2');

        userEvent.click(expandableRow);

        expect(getByText('Spotify')).toBeVisible();
        expect(getByText('Apple Music')).toBeVisible();

        const trackRowAfterToggle = getByText('Test Track 2');

        userEvent.click(trackRowAfterToggle);

        expect(queryByText('Spotify')).not.toBeInTheDocument();
        expect(queryByText('Apple Music')).not.toBeInTheDocument();
    });

    test('handle rows with internal links', () => {
        const { getByText, queryByText } = renderInAppContext(
            <MatchesTable
                trackMetadata={mockTrackMetadata}
                trackDataLoading={false}
                tableData={[mockTableData[0]]}
            />
        );

        const expandableRow = getByText('Test Track 1');

        userEvent.click(expandableRow);

        expect(getByText('123456789012')).toBeVisible();
        expect(queryByText('Spotify')).not.toBeInTheDocument();
        expect(queryByText('Apple Music')).not.toBeInTheDocument();
    });

    test('link href should match the songwhip link', () => {
        const { getByText, getByTestId } = renderInAppContext(
            <MatchesTable
                trackMetadata={mockTrackMetadata}
                trackDataLoading={false}
                tableData={mockTableData}
            />
        );

        const expandableRow = getByText('Test Track 2');

        userEvent.click(expandableRow);

        const spotifyLink = getByTestId(`${CLASS_NAME}-dspRow-Spotify`);

        expect(spotifyLink.querySelector('a')).toHaveAttribute(
            'href',
            'https://spotify.com/track/1'
        );
    });
});
