//Components
import estimate from "@/layouts/estimate/estimate.vue";
import { shallowMount } from "@vue/test-utils";
import { getMountOptions } from "@/helpers/unit-test-helper.js";

//Supporting files
import { storeKey } from "vuex";
import store from "@/store";
import { storeMutations } from "@/constants/store-mutations";
import { settleAllPromises } from "@/helpers/layout-helper.js";
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import baseMixin from "../../mixins/base-mixin";
import { vinLookupMethodSelections } from "@/constants/vin-lookup-method-selections.js";

// Mock our module for promises.
jest.mock("@/helpers/layout-helper.js", () => ({
    settleAllPromises: jest.fn(),
}));

// Mock fetchCmsContentForPage
jest.mock("@/helpers/cms-content-helper", () => ({
    fetchCmsContentForPage: jest.fn(),
}));

describe("estimate.vue", () => {
    test("Selected vin option is emitted upon selection.", async () => {
        //Arrange
        const { wrapper } = setupMocks({
            modelValueProp: ["Provide my VIN manually most specific to your vehicle"],
        });

        //Act
        wrapper.setValue({ modelValue: ["Provide my license plate # Most accurate VIN match"] });
        await wrapper.vm.$nextTick();

        //Assesrt
        expect(wrapper.emitted()["update:modelValue"][0]).toEqual([
            { modelValue: ["Provide my license plate # Most accurate VIN match"] },
        ]);
    });

    describe("move forward", () => {
        test("After selecting provide my home address on ForwardButtonAction triggers a router.navigateWithSaving", async () => {
            //Arrange
            const { wrapper } = setupMocks({});
            await wrapper.setData({
                selectedVinLookupMethod: vinLookupMethodSelections.HOMEADDRESS,
            });

            //Act
            wrapper.vm.forwardButtonAction();

            //Assert
            expect(wrapper.vm.$router.navigateWithSaving).toHaveBeenCalled();
        });

        test("After selecting provide my manual vin on ForwardButtonAction triggers a router.navigateWithSaving", async () => {
            //Arrange
            const { wrapper } = setupMocks({});
            await wrapper.setData({
                selectedVinLookupMethod: vinLookupMethodSelections.MANUALVIN,
            });

            store.commit(storeMutations.UPDATE_IS_REPAIR, false);
            store.commit(storeMutations.UPDATE_MAKE, "acura");

            //Act
            await wrapper.vm.forwardButtonAction();

            //Assert
            expect(wrapper.vm.$router.navigateWithSaving).toHaveBeenCalled();
        });

        test("Provide my license plate on ForwardButtonAction triggers a router.navigateWithSaving", async () => {
            //Arrange
            const { wrapper } = setupMocks({});
            await wrapper.setData({
                selectedVinLookupMethod: vinLookupMethodSelections.LICENSEPLATE,
            });

            //Act
            wrapper.vm.forwardButtonAction();

            //Assert
            expect(wrapper.vm.$router.navigateWithSaving).toHaveBeenCalled();
        });

        // TODO KO
        describe("isRepair", () => {
            test.todo("is repair and zip codes are valid/serviceable => go to quote page");
            test.todo(
                "is repair and zip codes are valid but not serviceable => show correct alert, remove loader"
            );
            test.todo(
                "is repair and zip codes are not valid/serviceable => show correct alert, remove loader"
            );
        });
    });

    test("BackButtonAction triggers a router.navigateWithoutSaving change", async () => {
        //Arrange
        const { wrapper } = setupMocks({});

        delete window.location;
        window.location = { search: "?fmgPage=estimate&zipcode=43015" };

        //Act
        estimate.beforeRouteEnter.call(
            wrapper.vm,
            { query: { fmgPage: "estimate" } },
            undefined,
            (c) => c(wrapper.vm)
        );

        wrapper.vm.backButtonAction();

        //Assert
        expect(wrapper.vm.$router.navigateWithoutSaving).toHaveBeenCalled();
    });

    describe("arePagePrerequisitesValid", () => {
        beforeEach(() => {
            store.commit(storeMutations.UPDATE_IS_REPAIR, false);
            store.commit(storeMutations.UPDATE_GLASS_TO_REPLACE, null);
        });

        test("isRepair is false and there are no glassToReplace => should return false", () => {
            // Arrange
            const { wrapper } = setupMocks({});
            store.commit(storeMutations.UPDATE_IS_REPAIR, false);
            store.commit(storeMutations.UPDATE_GLASS_TO_REPLACE, []);

            // Act
            let arePagePrerequisitesValid = wrapper.vm.arePagePrerequisitesValid();

            // Assert
            expect(arePagePrerequisitesValid).toBe(false);
        });

        test("isRepair is false and glassToReplace is null => should return false", () => {
            // Arrange
            const { wrapper } = setupMocks({});
            store.commit(storeMutations.UPDATE_IS_REPAIR, false);
            store.commit(storeMutations.UPDATE_GLASS_TO_REPLACE, null);

            // Act
            let arePagePrerequisitesValid = wrapper.vm.arePagePrerequisitesValid();

            // Assert
            expect(arePagePrerequisitesValid).toBe(false);
        });

        test("isRepair is false are there is one glassToReplace => should return true", () => {
            // Arrange
            const { wrapper } = setupMocks({});
            store.commit(storeMutations.UPDATE_IS_REPAIR, false);
            store.commit(storeMutations.UPDATE_GLASS_TO_REPLACE, [
                { glassLocation: "TEST", glassName: "NAME" },
            ]);

            // Act
            let arePagePrerequisitesValid = wrapper.vm.arePagePrerequisitesValid();

            // Assert
            expect(arePagePrerequisitesValid).toBe(true);
        });

        test("isRepair is false are there are multiple glassToReplace => should return true", () => {
            // Arrange
            const { wrapper } = setupMocks({});
            store.commit(storeMutations.UPDATE_IS_REPAIR, false);
            store.commit(storeMutations.UPDATE_GLASS_TO_REPLACE, [
                { glassLocation: "TEST1", glassName: "NAME1" },
                { glassLocation: "TEST2", glassName: "NAME2" },
                { glassLocation: "TEST3", glassName: "NAME3" },
            ]);

            // Act
            let arePagePrerequisitesValid = wrapper.vm.arePagePrerequisitesValid();

            // Assert
            expect(arePagePrerequisitesValid).toBe(true);
        });

        test("isRepair is set to null => arePagePrerequisitesValid should return false", async () => {
            // Arrange
            const { wrapper } = setupMocks({});
            store.commit(storeMutations.UPDATE_IS_REPAIR, null);

            // Act
            let arePagePrerequisitesValid = wrapper.vm.arePagePrerequisitesValid();

            // Assert
            expect(arePagePrerequisitesValid).toBe(false);
        });

        test("isRepair is set to true => arePagePrerequisitesValid should return true", async () => {
            // Arrange
            const { wrapper } = setupMocks({});
            store.commit(storeMutations.UPDATE_IS_REPAIR, true);

            // Act
            let arePagePrerequisitesValid = wrapper.vm.arePagePrerequisitesValid();

            // Assert
            expect(arePagePrerequisitesValid).toBe(true);
        });
    });

    test("Changing zip should reset alert", async () => {
        //Arrange
        const { wrapper } = setupMocks({});

        //Act
        wrapper.vm.displayNonServiceableZipAlert = "true";
        wrapper.vm.serviceZipCode = "43015";

        await wrapper.vm.$nextTick();

        //Assert
        expect(wrapper.vm.displayNonServiceableZipAlert).toEqual(false);
    });
});

describe("test alertInfo and isRepair", () => {
    const skipOptions = [
        [true, false, "AlertQuoteReady"],
        [false, true, "AlertQuoteVinOptional"],
        [false, false, "AlertQuoteReady"],
        [true, true, "AlertQuoteVinOptional"],
    ];
    test.each(skipOptions)(
        "isRepair %s, skipVinNotRepair %s alertInfo should return %s",
        async (isRepair, skipVinNotRepair, expectedAlertInfo) => {
            const { wrapper } = setupMocks({});
            await wrapper.setData({
                skipVinNotRepair: skipVinNotRepair,
            });

            store.commit(storeMutations.UPDATE_IS_REPAIR, isRepair);

            expect(wrapper.vm.alertInfo).toEqual(expectedAlertInfo);
            expect(wrapper.vm.isRepair).toEqual(isRepair);
        }
    );
});

function setupMocks({
    groupName = "estimate",
    skipVin = false,
    cmsQuestionText = "Let's get your VIN. Or we can look it up for you!",
    cmsAnswers = [
        { Name: "Provide my VIN manually Most specific to your vehicle" },
        { Name: "Provide my license plate # Most accurate VIN match" },
        { Name: "Provide my home address Most convenient VIN match" },
    ],
    funnelFooterWidget = { ForwardButtonText: "test txt" },
    mountOptionsMockData = {
        router: {
            navigate: jest.fn(),
            navigateWithSaving: jest.fn(),
            navigateWithoutSaving: jest.fn(),
        },
        route: {
            query: {},
        },
    },
}) {
    //Mock CMS Content
    const cmsContent = {
        groupName: groupName,
        QuestionText: cmsQuestionText,
        Answers: cmsAnswers,
        FunnelFooterWidget: funnelFooterWidget,
    };

    const apiPromise = Promise.resolve({ cmsContent });
    settleAllPromises.mockImplementation(() => apiPromise);
    fetchCmsContentForPage.mockImplementation(() => Promise.resolve());

    const mountOptions = getMountOptions({ ...mountOptionsMockData, mixins: [baseMixin] });
    mountOptions["attachTo"] = document.body;

    const wrapper = shallowMount(estimate, mountOptions);
    wrapper.vm.skipVin = skipVin;
    wrapper.vm.getZipCodeData = jest
        .fn()
        .mockReturnValue({ isValid: true, isServiceable: true, state: "OH" });

    return { wrapper, apiPromise };
}
