import { test, expect } from "../../fixtures/index";
import { DashboardPage } from "../../pom/dashboard.page";
import { LoginPage } from "../../pom/login.page";

test.describe("Function case for contact tests", async () => {
    let loginPage: LoginPage;
    let dashboardPage: DashboardPage;

    test.beforeEach(async ({ page, conf }) => {
        loginPage = new LoginPage(page);
        dashboardPage = new DashboardPage(page);

        await loginPage.open();
        await loginPage.login(conf.data.username, conf.data.password);
        await expect(loginPage.baseLoc.dashboardContainer).toBeVisible();
    });

    test("DASHBOARD_001 - Verify when change page had change the title", {
        tag: ['@DASHBOARD_001', '@dashboard', '@function']
    }, async () => {
        for (const { name, link } of dashboardPage.pages) {
            await test.step(`Verify page ${name} avaible`, async () => {
                await dashboardPage.go(link);
                await expect(dashboardPage.dashboardLoc.namePage).toContainText(name);
                console.log("Title", await dashboardPage.page.title())
                expect(await dashboardPage.page.title()).toContain(name)
            })
        }
    })

    test("DASHBOARD_002 - Verify when click search requests in the columns status detail", {
        tag: ['@DASHBOARD_002', '@dashboard', '@function']
    }, async () => {
        await test.step("Choose Tab All request and filter by Year to Date", async () => {
            await dashboardPage.dashboardLoc.monitorTab("TAB_MY_TEAM_HUB_ON_DASHBOARD").click();
            await dashboardPage.dashboardLoc.filterMonitor.arrowDropdown(2).click();
            await dashboardPage.dashboardLoc.filterMonitor.dropdownFilterOption("Year to Date").click()
        })

        await test.step("Click on the chart item 'TeamxRequest' and verify the request list", async () => {
            await dashboardPage.dashboardLoc.filterMonitor.itemChartTeamRequest.click();
            await expect(dashboardPage.dashboardLoc.filterMonitor.tabRequest("Team Request")).toHaveClass(/active/);
        })

        await test.step("Click on the chart item 'SharedxWithxTeam' and verify the request list", async () => {
            await dashboardPage.go("");
            await dashboardPage.dashboardLoc.filterMonitor.itemChartShareWithTeam.click();
            await expect(dashboardPage.dashboardLoc.filterMonitor.tabRequest("Shared with Team")).toHaveClass(/active/);
        })
    })

    test("DASHBOARD_003 - Verify navbar active in tablet and phone", {
        tag: ['@DASHBOARD_003', '@dashboard', '@function']
    }, async ({ browser, conf }) => {
        for (const { name, viewport } of dashboardPage.devices) {
            await test.step(`Verify navbar active in ${name}`, async () => {
                const context = await browser.newContext({
                    viewport: viewport,
                    userAgent: name.includes('iPhone') || name.includes('iPad')
                        ? 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1'
                        : 'Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Mobile Safari/537.36',
                    deviceScaleFactor: name.includes('iPhone') || name.includes('iPad') ? 2 : 1,
                    isMobile: true,
                    hasTouch: true,
                });

                const newPage = await context.newPage();
                const newDashboardPage = new DashboardPage(newPage);
                const newLoginPage = new LoginPage(newPage);

                await newLoginPage.open();
                await newLoginPage.login(conf.data.username, conf.data.password);
                await expect(newLoginPage.baseLoc.dashboardContainer).toBeVisible();

                await newDashboardPage.dashboardLoc.showNavBarIcon.click();

                const checkTabVisibility = async (tabs: any) => {
                    for (const tab of tabs) {
                        const navLink = newDashboardPage.dashboardLoc.navLink(tab.name);
                        await navLink.scrollIntoViewIfNeeded();
                        await expect(navLink).toBeVisible({ timeout: 5000 });

                        if (tab.subTabs) {
                            await navLink.click({ force: true });
                            await newDashboardPage.waitForSecond(2);
                            for (const subTab of tab.subTabs) {
                                const subNavLink = newDashboardPage.dashboardLoc.subNavLink(subTab);
                                const isPresent = await subNavLink.count() > 0;
                                if (isPresent) {
                                    await expect(subNavLink).toBeVisible({ timeout: 5000 });
                                }
                            }
                        }
                    }
                };

                await checkTabVisibility(newDashboardPage.navbarTabs.tabs);

                await newPage.close();
                await context.close();
            });
        }
    });

    test("DASHBOARD_004 - Verify all modal filter click reset not to close", {
        tag: ['@DASHBOARD_004', '@dashboard', '@function']
    }, async () => {
        const popupSuggestContacts = dashboardPage.dashboardLoc.modal.headerModal("Suggested Contacts");
        await dashboardPage.page.addLocatorHandler(popupSuggestContacts, async () => {
            await dashboardPage.dashboardLoc.buttonByText("Skip Now").click();
        });

        for (const { name, link } of dashboardPage.pageFilter) {
            await test.step(`Verify when click reset filter in ${name} page`, async () => {
                await dashboardPage.go(link);
                await dashboardPage.dashboardLoc.search.filter.btn.click();
                await expect(dashboardPage.dashboardLoc.modal.headerModal("Filter")).toBeVisible();
                await dashboardPage.dashboardLoc.search.filter.popup.btnReset.click();
                await dashboardPage.waitForSecond(1);
                await expect(dashboardPage.dashboardLoc.modal.headerModal("Filter")).toBeVisible();
                await dashboardPage.waitForSecond(1);
                await dashboardPage.dashboardLoc.search.filter.popup.btnClose.click();
                await expect(dashboardPage.dashboardLoc.modal.headerModal("Filter")).not.toBeVisible();
            })
        }
    });

    test("DASHBOARD_005 - Verify Year to Date and Custom date", {
        tag: ['@DASHBOARD_005', '@dashboard', '@function']
    }, async () => {
        let totalRequestLOP: number = 0;
        await test.step("Filter Year to Date", async () => {
            await dashboardPage.dashboardLoc.detail.statusDetailsInput.nth(1).click();
            await expect(dashboardPage.dashboardLoc.common.spanText("Year to Date").last()).toBeVisible();
            await dashboardPage.dashboardLoc.common.spanText("Year to Date").last().click();
            await expect(dashboardPage.dashboardLoc.filterMonitor.requestTypeNumber.first()).toBeVisible();
            await dashboardPage.waitForSecond(2);
            const textRequestLOP = await dashboardPage.dashboardLoc.filterMonitor.requestTypeNumber.first().innerText();
            totalRequestLOP = parseInt(textRequestLOP);
        });

        await test.step("Filter Custom Date", async () => {
            await dashboardPage.dashboardLoc.detail.statusDetailsInput.nth(1).click();
            await expect(dashboardPage.dashboardLoc.common.spanText("Custom").last()).toBeVisible();
            await dashboardPage.dashboardLoc.common.spanText("Custom").last().click();
            await dashboardPage.dashboardLoc.modal.inputByID("date_time_created_from").fill("01/01/2025");

            // Fill to date today
            const today = new Date();
            const day = String(today.getDate()).padStart(2, '0');
            const month = String(today.getMonth() + 1).padStart(2, '0');
            const year = today.getFullYear();
            const formattedDate = `${month}/${day}/${year}`;
            await dashboardPage.dashboardLoc.modal.inputByID("date_time_created_to").fill(formattedDate);
            await dashboardPage.dashboardLoc.buttonByText("Apply").click();
            await expect(dashboardPage.dashboardLoc.filterMonitor.requestTypeNumber.first()).toBeVisible();
            await dashboardPage.waitForSecond(2);
            const textRequestLOPCustom = await dashboardPage.dashboardLoc.filterMonitor.requestTypeNumber.first().innerText();
            const totalRequestLOPCustom = parseInt(textRequestLOPCustom);
            expect(totalRequestLOPCustom).toBe(totalRequestLOP);
        });
    })

    test("GS_001 - Verify search by Case", {
        tag: ['@GS_001', '@dashboard', '@function']
    }, async ({ conf }) => {
        await test.step("Verify search case unarchive (have 1 request archive, 1 request unarchive)", async () => {
            await dashboardPage.openGlobalSearch();
            await dashboardPage.dashboardLoc.iconSearchGlobal.click();
            await dashboardPage.dashboardLoc.inputSearchGlobal.type(conf.data.case_unarchive, { delay: 100 });

            // Sử dụng tạm toMatchAriaSnapshot vì element hiển thị duplicate
            await expect(dashboardPage.page.getByRole('banner')).toMatchAriaSnapshot(dashboardPage.dashboardSnapshot.globalSearchCaseUnarchive);
            await dashboardPage.dashboardLoc.inputSearchGlobal.fill("");
        });

        await test.step("Verify search case archive", async () => {
            await dashboardPage.dashboardLoc.inputSearchGlobal.type(conf.data.case_archive, { delay: 100 });
            await expect(dashboardPage.dashboardLoc.boxNoDataGlobalSearch.last()).toBeVisible();
        });
    });

    test("GS_002 - Verify search by request", {
        tag: ['@GS_002', '@dashboard', '@function']
    }, async ({ conf }) => {
        await test.step("Verify search request unarchive", async () => {
            await dashboardPage.openGlobalSearch();
            await dashboardPage.dashboardLoc.inputSearchGlobal.type(conf.data.request_unarchive, { delay: 100 });

            // Sử dụng tạm toMatchAriaSnapshot vì element hiển thị duplicate
            await expect(dashboardPage.page.getByRole('banner')).toMatchAriaSnapshot(dashboardPage.dashboardSnapshot.globalSearchRequestUnarchive);
            await dashboardPage.dashboardLoc.inputSearchGlobal.fill("");
        });

        await test.step("Verify search request archive", async () => {
            await dashboardPage.dashboardLoc.inputSearchGlobal.type(conf.data.request_archive, { delay: 100 });
            await expect(dashboardPage.dashboardLoc.boxNoDataGlobalSearch.last()).toBeVisible();
        });
    });

    test("GS_003 - Verify search by client name", {
        tag: ['@GS_003', '@dashboard', '@function']
    }, async ({ conf }) => {
        await test.step("Verify search client hace case unarchive", async () => {
            await dashboardPage.openGlobalSearch();
            await dashboardPage.dashboardLoc.inputSearchGlobal.type(conf.data.client_had_case_archive, { delay: 100 });
            await expect(dashboardPage.dashboardLoc.boxNoDataGlobalSearch.last()).toBeVisible();
            await dashboardPage.dashboardLoc.inputSearchGlobal.fill("");
        });

        await test.step("Verify search client dont have case", async () => {
            await dashboardPage.dashboardLoc.inputSearchGlobal.type(conf.data.client_dont_have_case, { delay: 100 });
            await expect(dashboardPage.dashboardLoc.boxNoDataGlobalSearch.last()).toBeVisible();
            await dashboardPage.dashboardLoc.inputSearchGlobal.fill("");
        });

        await test.step("Verify search client hace case archive", async () => {
            await dashboardPage.dashboardLoc.inputSearchGlobal.type(conf.data.client_had_case_unarchive, { delay: 100 });

            // Sử dụng tạm toMatchAriaSnapshot vì element hiển thị duplicate
            await expect(dashboardPage.page.getByRole('banner')).toMatchAriaSnapshot(dashboardPage.dashboardSnapshot.globalSearchClientHadCaseUnarchive);
        });
    });

    test("GS_004 - Verify search by date", {
        tag: ['@GS_004', '@dashboard', '@function']
    }, async ({ conf }) => {
        await test.step("Verify search by DOI, DOB unarchive", async () => {
            //Search case unarchive by DOI
            await dashboardPage.openGlobalSearch();
            await dashboardPage.dashboardLoc.inputSearchGlobal.type(conf.data.doi, { delay: 100 });

            await expect(dashboardPage.page.getByRole('banner')).toMatchAriaSnapshot(dashboardPage.dashboardSnapshot.globalSearchClientHadCaseUnarchive);

            // Search case unarchive by DOB
            await dashboardPage.dashboardLoc.inputSearchGlobal.fill("");
            await dashboardPage.dashboardLoc.inputSearchGlobal.type(conf.data.dob, { delay: 100 });

            await expect(dashboardPage.page.getByRole('banner')).toMatchAriaSnapshot(dashboardPage.dashboardSnapshot.globalSearchClientHadCaseUnarchive);
            await dashboardPage.dashboardLoc.inputSearchGlobal.fill("");
        });

        await test.step("Verify search by DOI, DOB archive", async () => {
            //Search case archive by DOI
            await dashboardPage.dashboardLoc.inputSearchGlobal.type(conf.data.doi_case_archive, { delay: 100 });
            await expect(dashboardPage.dashboardLoc.boxNoDataGlobalSearch.last()).toBeVisible();
            await dashboardPage.dashboardLoc.inputSearchGlobal.fill("");

            // Search case archive by DOB
            await dashboardPage.dashboardLoc.inputSearchGlobal.type(conf.data.dob_case_archive, { delay: 100 });
            await expect(dashboardPage.dashboardLoc.boxNoDataGlobalSearch.last()).toBeVisible();
        });
    })
})