import { test, expect } from '@playwright/test';
import { BASE_URL, ADMIN, FINANCE, loginAs } from '../helpers';

test.describe('WFBO Master Agents', () => {

    test.beforeEach(async ({ page }) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
    });

    test('admin can access /wfbo/master-agents', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/master-agents`);
        // Page renders without error — sidebar should be visible
        await expect(page.locator('[data-testid="wfbo-sidebar"]')).toBeVisible();
    });

    test('AGENT fixture appears as a master agent tree node', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/master-agents`);
        const masterNodes = page.locator('[data-testid^="tree-master-"]');
        await expect(masterNodes.first()).toBeVisible();
    });

    test('master agent tree node shows total downline deposits', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/master-agents`);
        const masterNode = page.locator('[data-testid^="tree-master-"]').first();
        await expect(masterNode).toBeVisible();
        await expect(masterNode).toContainText('Total Deposits');
    });

    test('FINANCE user is blocked from /wfbo/master-agents', async ({ page }) => {
        await loginAs(page, FINANCE.mobile, FINANCE.password);
        await page.goto(`${BASE_URL}/wfbo/master-agents`);
        // FINANCE does not have ROLE_ADMIN — should not see master agent nodes
        await expect(page.locator('[data-testid^="tree-master-"]')).not.toBeVisible();
    });

    test('agent reassign modal opens when clicking Reassign button', async ({ page }) => {
        // Use search to auto-expand all tree nodes (template adds is-open class when search is truthy)
        await page.goto(`${BASE_URL}/wfbo/master-agents?search=Agent`);

        // Reassign button is now visible in the expanded tree (auto-expanded via search)
        const reassignBtn = page.locator('[data-testid^="btn-reassign-agent-"]').first();
        if (await reassignBtn.count() === 0) {
            test.skip();
            return;
        }
        await reassignBtn.scrollIntoViewIfNeeded();
        await reassignBtn.click({ force: true });
        await expect(page.locator('[data-testid="reassign-modal"]')).toHaveCSS('display', 'flex');
    });

    test('agent reassignment succeeds when a different master agent is selected', async ({ page }) => {
        // Use search to auto-expand all tree nodes
        await page.goto(`${BASE_URL}/wfbo/master-agents?search=Agent`);

        const reassignBtn = page.locator('[data-testid^="btn-reassign-agent-"]').first();
        if (await reassignBtn.count() === 0) {
            test.skip();
            return;
        }
        await reassignBtn.scrollIntoViewIfNeeded();
        await reassignBtn.click({ force: true });

        const modal = page.locator('[data-testid="reassign-modal"]');
        await expect(modal).toHaveCSS('display', 'flex');

        const selectMaster = page.locator('#select-master');
        const options = await selectMaster.locator('option[value]').all();
        // Need at least one valid master agent option
        if (options.length === 0) {
            test.skip();
            return;
        }
        const firstOptionValue = await options[0].getAttribute('value');
        if (!firstOptionValue) {
            test.skip();
            return;
        }
        await selectMaster.selectOption(firstOptionValue);
        await page.click('[data-testid="btn-reassign-confirm"]');
        await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();
    });

    test('admin can promote a plain user to master agent from users list', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/users`);

        // Find a user row that has a promote-agent form AND is actually promotable
        // (not already a master agent). Iterate rows until we find one whose actions
        // dropdown contains the promote button.
        const rows = page.locator('[data-testid^="user-row-"]');
        const rowCount = await rows.count();

        let promoted = false;
        for (let i = 0; i < rowCount; i++) {
            const row = rows.nth(i);
            const rowTestId = await row.getAttribute('data-testid');
            const userId = rowTestId?.replace('user-row-', '');
            if (!userId) continue;

            const promoteForm = page.locator(`[data-testid="form-promote-agent-${userId}"]`);
            if (await promoteForm.count() === 0) continue;

            // Open the actions dropdown
            await row.locator(`[data-testid="btn-actions-${userId}"]`).click();

            // Check if the promote button appeared
            const promoteBtn = page.locator(`[data-testid="btn-promote-agent-${userId}"]`);
            try {
                await promoteBtn.waitFor({ state: 'visible', timeout: 2000 });
            } catch {
                // Close any open dropdown before trying next row
                await page.keyboard.press('Escape');
                continue;
            }

            await promoteBtn.click();

            // Confirm the action in the confirmation modal
            const confirmBtn = page.locator('[data-testid="btn-confirm-action"]');
            await expect(confirmBtn).toBeVisible();
            await confirmBtn.click();

            await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();
            promoted = true;
            break;
        }

        if (!promoted) {
            test.skip('No promotable user found');
        }
    });

    test('admin can demote an agent via users list', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/users`);

        const demoteForm = page.locator('[data-testid^="form-demote-agent-"]').first();
        if (await demoteForm.count() === 0) {
            test.skip();
            return;
        }

        const formTestId = await demoteForm.getAttribute('data-testid');
        const userId = formTestId?.replace('form-demote-agent-', '');

        await page.locator(`[data-testid="btn-actions-${userId}"]`).click();
        await page.locator(`[data-testid="btn-demote-agent-${userId}"]`).waitFor({ state: 'visible' });
        await page.locator(`[data-testid="btn-demote-agent-${userId}"]`).click();

        await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();
    });

    test('admin can change a user\'s assigned agent', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/users`);

        const changeBtn = page.locator('[data-testid^="btn-change-agent-"]').first();
        if (await changeBtn.count() === 0) {
            test.skip();
            return;
        }

        // Get the userId and open their dropdown first
        const btnTestId = await changeBtn.getAttribute('data-testid');
        const userId = btnTestId?.replace('btn-change-agent-', '');

        // Open the actions dropdown for this user
        await page.locator(`[data-testid="btn-actions-${userId}"]`).click();

        // Click the change-agent button (now visible in open dropdown)
        await changeBtn.click({ force: true });

        // Wait for Bootstrap modal to appear
        const modal = page.locator('#changeAgentModal');
        await expect(modal).toBeVisible();

        // Select first available master agent from the dropdown
        const select = page.locator('#changeAgentSelect');
        const options = await select.locator('option[value]:not([value=""])').all();
        if (options.length === 0) {
            test.skip();
            return;
        }
        const firstVal = await options[0].getAttribute('value');
        await select.selectOption(firstVal!);

        // Submit the modal form
        await modal.locator('button[type="submit"]').click();
        await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();
    });

});
