import React from 'react';
import { fireEvent } from '@testing-library/react';
import { renderInAppContext } from '@theorchard/suite-testing';
import { getMergedProduct, getProductMetadata } from 'lib/mockProductData';
import ProductModalHeader, { CLASS_NAME, Props } from '../productModalHeader';

describe('<ProductModalHeader>', () => {
    const defaultProps: Props = {
        product: getProductMetadata(),
        mergedProduct: getMergedProduct({
            productId: 123456,
            productName: 'the best name',
            upc: '1234567890',
            saleStartDate: '5/1/2025',
            preorderDate: '1/1/2025',
            label: {
                id: { vendorId: 123, subaccountId: 333 },
                name: 'Some label name',
                contentReviewNote: null,
                vendor: {
                    contentReviewNote: null,
                    name: 'Another name',
                    serviceTier: {
                        displayName: 'Some Tier',
                        name: 'some-tier',
                    },
                },
            },
            artists: [
                {
                    artistId: '4325',
                    artistName: 'Michael Jackson',
                    artistType: 'writer',
                },
                {
                    artistId: '4326',
                    artistName: 'Jason Derulo',
                    artistType: 'primary_artist',
                },
            ],
        }),
        submissionType: 'new',
        queueName: 'initial',
        isSubmittingReview: false,
        onQueueMove: jest.fn(),
        productTargetGroup: null,
        isApprovalNoteRequired: false,
        isApprovalBlocked: false,
        isRejectionBlocked: false,
        isReviewHistoryDisabled: false,
        productReviewQueueId: 1,
        onReviewCompleted: jest.fn(),
        submittedByUserLanguage: null,
        sidebarRef: { current: null },
        lockedProductError: false,
        wasExistingLockDetected: false,
    };

    const renderComponent = (customProps?: Partial<Props>) =>
        renderInAppContext(
            <ProductModalHeader {...defaultProps} {...customProps} />
        );

    test('renders with no errors', () => {
        const { getAllByTestId } = renderComponent();

        const componentEl = getAllByTestId(CLASS_NAME)[0];

        expect(componentEl).toBeInTheDocument();

        expect(componentEl).toHaveTextContent('1234567890');
        expect(componentEl).toHaveTextContent('123456');
        expect(componentEl).toHaveTextContent('Some Tier');
        expect(componentEl).toHaveTextContent('the best name');
        expect(componentEl).toHaveTextContent('Sales Start Date');
        expect(componentEl).toHaveTextContent('01 May 2025');
        expect(componentEl).toHaveTextContent('Pre-order Date');
        expect(componentEl).toHaveTextContent('01 Jan 2025');
        expect(componentEl).toHaveTextContent('Jason Derulo');
        expect(
            getAllByTestId(`${CLASS_NAME}-submissionType`)[0]
        ).toHaveTextContent('New Submission');
        expect(
            getAllByTestId('queue-move-action-button')[0]
        ).toBeInTheDocument();
        expect(getAllByTestId('reject-button')[0]).toBeInTheDocument();
        expect(getAllByTestId('approve-button')[0]).toBeInTheDocument();
        expect(getAllByTestId('approve-button')[0]).toBeEnabled();
        expect(getAllByTestId('review-history-button')[0]).toBeInTheDocument();
    });

    test('handles null scheduling dates', () => {
        const mockProduct = getMergedProduct({
            saleStartDate: null,
            preorderDate: null,
            label: {
                id: { vendorId: 123, subaccountId: 333 },
                name: 'Some label name',
                contentReviewNote: null,
                vendor: {
                    contentReviewNote: null,
                    name: 'Another name',
                    serviceTier: null,
                },
            },
        });
        const { getAllByTestId } = renderComponent({
            mergedProduct: mockProduct,
        });
        const componentEl = getAllByTestId(CLASS_NAME)[0];
        expect(componentEl).toHaveTextContent('Sales Start Date');
        expect(componentEl).toHaveTextContent('Pre-order Date');
    });

    test('renders basicAccountInfo popover when Account Pill is clicked', () => {
        const { getByTestId } = renderComponent();
        const accountPill = getByTestId('Popover');

        fireEvent.click(accountPill);

        expect(getByTestId('BasicAccountInfo')).toBeInTheDocument();
    });

    describe('approve button', () => {
        test('blocks approval', () => {
            const { getAllByTestId } = renderComponent({
                isApprovalBlocked: true,
            });
            expect(getAllByTestId('approve-button')[0]).toBeInTheDocument();
            expect(getAllByTestId('approve-button')[0]).toBeDisabled();
        });

        test('renders approval sidecar', async () => {
            const { getAllByRole, queryByTestId, findByTestId } =
                renderComponent();
            const approveButtons = getAllByRole('button', { name: 'Approve' });
            const approveButton = approveButtons[0];
            let approvalSidecar = queryByTestId('ProductModalApprovalSidecar');
            expect(approveButton).toBeInTheDocument();
            expect(approvalSidecar).not.toBeInTheDocument();
            fireEvent.click(approveButton);
            approvalSidecar = await findByTestId('ProductModalApprovalSidecar');
            expect(approvalSidecar).toBeInTheDocument();
        });
    });

    describe('product review history', () => {
        test('review history button is disabled', () => {
            const { getAllByTestId } = renderComponent({
                product: getProductMetadata({
                    reviewHistory: {
                        items: [
                            {
                                createdDatetime: '2024-05-14T19:19:26.000000Z',
                                destinationQueueName: null,
                                escalationType: null,
                                note: null,
                                queueName: 'initial',
                                reviewQueueId: 1,
                                submissionCount: 1,
                                submissionType: 'new',
                                userAction: 'submission',
                                userInfo: null,
                            },
                        ],
                        totalCount: 1,
                    },
                }),
            });
            const reviewHistoryButton = getAllByTestId(
                'review-history-button'
            )[0];
            expect(reviewHistoryButton).toBeVisible();
            expect(reviewHistoryButton).toBeDisabled();
        });

        test('review history button is enabled', () => {
            const { getAllByTestId } = renderComponent();
            const reviewHistoryButton = getAllByTestId(
                'review-history-button'
            )[0];
            expect(reviewHistoryButton).toBeVisible();
            expect(reviewHistoryButton).toBeEnabled();
        });

        test('isReviewHistoryDisabled prop', () => {
            const { getAllByTestId } = renderComponent({
                isReviewHistoryDisabled: true,
            });
            const reviewHistoryButton = getAllByTestId(
                'review-history-button'
            )[0];
            expect(reviewHistoryButton).toBeInTheDocument();
            expect(reviewHistoryButton).toBeDisabled();
        });
    });

    describe('cover art', () => {
        test('displays revised artwork when available', () => {
            const { getAllByTestId } = renderComponent();
            const coverArt = getAllByTestId('CoverArt')[0];
            const artwork = coverArt.querySelector('.CoverArt-image');
            expect(artwork).toBeVisible();
            expect(artwork?.getAttribute('src')).toEqual(
                'http:/path/to/revised/img'
            );
        });

        test('displays original artwork when no revised artwork', () => {
            const { getAllByTestId } = renderComponent({
                mergedProduct: getMergedProduct({
                    releaseCorrection: {
                        items: [],
                    },
                }),
            });
            const coverArt = getAllByTestId('CoverArt')[0];
            const artwork = coverArt.querySelector('.CoverArt-image');
            expect(artwork).toBeVisible();
            expect(artwork?.getAttribute('src')).toEqual('http:/path/to/img');
        });
    });

    describe('locked product', () => {
        test('all actions are disabled', () => {
            const { getAllByTestId } = renderComponent({
                lockedProductError: true,
                wasExistingLockDetected: true,
            });
            expect(getAllByTestId('approve-button')[0]).toBeInTheDocument();
            expect(getAllByTestId('approve-button')[0]).toBeDisabled();

            expect(getAllByTestId('reject-button')[0]).toBeInTheDocument();
            expect(getAllByTestId('reject-button')[0]).toBeDisabled();

            expect(
                getAllByTestId('queue-move-action-button')[0]
            ).toBeInTheDocument();
            expect(
                getAllByTestId('queue-move-action-button')[0]
            ).toBeDisabled();

            const link = getAllByTestId('oa-edit-link')[0];
            expect(link).toBeInTheDocument();
            expect(link).toHaveAttribute('aria-disabled', 'true');
            expect(link).not.toHaveAttribute('href');
            expect(link).toHaveClass('oa-edit--disabled');
        });
    });
});
