//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";
import { experimentSettings } from "@/constants/experiments";
import { nextTick } from "vue";

// 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(),
}));

global.crypto = { randomUUID: 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();
        });

        test("Selecting no vin on ForwardButtonAction triggers a router.navigateWithSaving", async () => {
            //Arrange
            const { wrapper } = setupMocks({});
            await wrapper.setData({
                selectedVinLookupMethod: vinLookupMethodSelections.DECLINE,
            });

            //Act
            wrapper.vm.forwardButtonAction();

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

    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);
        });
    });
});

describe("estimate.vue", () => {
    test("should call forwardButtonAction if isExternalParameter is true and form is valid", async () => {
        store.getters = {
            externalParameterState: { isExternalParameter: true },
            externalParameterEstimate: { vinSelection: "decline" },
        };
        // Set up the component
        const { wrapper } = setupMocks({});

        wrapper.vm.forwardButtonAction = jest.fn();

        const nextFunction = jest.fn((c) => {
            c(wrapper.vm);
        });
        // Call the method that contains the if-else logic
        await estimate.beforeRouteEnter.call(
            wrapper.vm,
            { query: { fmgPage: "estimate" } },
            undefined,
            nextFunction
        );
        await wrapper.vm.$nextTick();

        expect(nextFunction).toHaveBeenCalled();
        expect(baseMixin.methods.isFormValid).toHaveBeenCalled();
        expect(baseMixin.methods.isFormValid()).toBe(true);
        await wrapper.vm.$nextTick();
        expect(wrapper.vm.forwardButtonAction).toHaveBeenCalled();
    });
});

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" },
        { Name: "I'd rather not share my VIN" },
    ],
    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 mockMixin = {
        methods: {
            getSettingValue: jest.fn((settingName) => {
                if (settingName === experimentSettings.IS_EMAIL_OPTIONAL) {
                    return "true";
                }
                return "false";
            }),
        },
    };
    const apiPromise = Promise.resolve({ cmsContent });
    settleAllPromises.mockImplementation(() => apiPromise);
    fetchCmsContentForPage.mockImplementation(() => Promise.resolve());
    baseMixin.methods.isFormValid = jest.fn().mockReturnValue(true);
    const mountOptions = getMountOptions({
        ...mountOptionsMockData,
        mixins: [baseMixin, mockMixin],
    });
    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 };
}
