import React from 'react';
import { MockedProvider } from '@apollo/client/testing';
import { fireEvent, waitFor } from '@testing-library/react';
import { renderInAppContext } from '@theorchard/suite-testing';
import { createMemoryHistory, MemoryHistory } from 'history';
import { getProductMetadata } from 'lib/mockProductData';
import { mockDeliveryStoresV2Data } from 'lib/test/mocks/deliveryStoresV2';
import { Router } from 'react-router-dom';
import * as deliveryRestrictionsQuery from 'src/data/queries/deliveryRestrictions/deliveryRestrictions';
import * as deliveryStoresV2Query from 'src/data/queries/deliveryStoresV2/deliveryStoresV2';
import * as territories from 'src/data/queries/territories/territories';
import ProductViewDeliveryRestrictions from '../productViewDeliveryRestrictions';

const defaultProduct = getProductMetadata();
let history: MemoryHistory | null = null;

const deliveryStoresV2Result = {
    loading: false,
    error: undefined,
    data: mockDeliveryStoresV2Data.items,
};

const deliveryRestrictionsResult = {
    loading: false,
    error: undefined,
    data: {
        productId: 123,
        deliveryRestrictions: [
            {
                deliveryStoreRestrictions: [],
                territoryRestrictions: [],
                deliveryStoreCountryRestrictions: [],
                newStoreOptOuts: null,
            },
        ],
        label: {
            activeDeliveryRestrictions: [
                {
                    deliveryStoreRestrictions: [
                        {
                            deliveryStore: { id: '101' },
                            distributionTypes: [{ id: 1 }, { id: 2 }],
                        },
                    ],
                    territoryRestrictions: [
                        {
                            territory: {
                                continent: 'North America',
                                orchId: '1',
                                countryName: 'United State',
                                territoryName: 'United States of America',
                                territoryCodeA2: 'US',
                                territoryCodeA3: 'USA',
                            },
                        },
                    ],
                    deliveryStoreCountryRestrictions: [
                        {
                            deliveryStore: { id: '101' },
                            territories: [
                                {
                                    continent: 'North America',
                                    orchId: '2',
                                    countryName: 'Canada',
                                    territoryName: 'Canada',
                                    territoryCodeA2: 'CA',
                                    territoryCodeA3: 'CA',
                                },
                            ],
                        },
                    ],
                    newStoreOptOuts: null,
                },
            ],
        },
    },
};

const territoriesResult = {
    loading: false,
    error: undefined,
    data: [
        {
            __typename: 'Territory',
            countryName: 'United States',
            territoryCodeA2: 'US',
            territoryName: 'United States of America',
            continent: 'North America',
        },
        {
            __typename: 'Territory',
            continent: 'North America',
            countryName: 'Canada',
            territoryCodeA2: 'CA',
            territoryName: 'Canada',
        },
    ],
} as unknown as ReturnType<typeof territories.useTerritoriesQuery>;

describe('<ProductViewDeliveryRestrictions>', () => {
    beforeEach(() => {
        jest.spyOn(
            deliveryStoresV2Query,
            'useDeliveryStoresV2Query'
        ).mockReturnValue(deliveryStoresV2Result);

        jest.spyOn(
            deliveryRestrictionsQuery,
            'useDeliveryRestrictionsQuery'
        ).mockReturnValue(deliveryRestrictionsResult);

        jest.spyOn(territories, 'useTerritoriesQuery').mockReturnValue(
            territoriesResult
        );
    });

    afterEach(() => jest.resetAllMocks());

    const renderComponent = () => {
        history = createMemoryHistory({ initialEntries: [''] });
        return renderInAppContext(
            <Router history={history}>
                <MockedProvider>
                    <ProductViewDeliveryRestrictions
                        product={defaultProduct}
                        onFingerprintRulesUpdated={jest.fn()}
                    />
                </MockedProvider>
            </Router>
        );
    };

    test('looks good', () => {
        const { getByText } = renderComponent();
        expect(
            getByText(
                $t(`contentReview.productViewDeliveryRestrictions.delivery`)
            )
        ).toBeVisible();
        expect(
            getByText(
                $t(
                    `contentReview.productViewDeliveryRestrictions.deliveryRestrictions`
                )
            )
        ).toBeVisible();
        expect(
            getByText(
                $t(
                    `contentReview.productViewDeliveryRestrictions.countryRestrictions`
                )
            )
        ).toBeVisible();
        expect(
            getByText(
                $t(
                    `contentReview.productViewDeliveryRestrictions.serviceRestrictions`
                )
            )
        ).toBeVisible();
        expect(
            getByText(
                $t(
                    `contentReview.productViewDeliveryRestrictions.countryByService`
                )
            )
        ).toBeVisible();
    });

    test('navigate to country restrictions tab', async () => {
        const { getByTestId } = renderComponent();
        const serviceNavLink =
            getByTestId('NavItem-country').querySelector('.nav-link');

        expect(history!.location.search).toBe('');
        expect(serviceNavLink).toBeInTheDocument();

        if (serviceNavLink) fireEvent.click(serviceNavLink);

        await waitFor(() => {
            expect(history!.location.search).toBe('?tab=country');
        });
    });
});
