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

test.describe('WFBO Withdrawal Management', () => {

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

    test('withdrawals page loads with table', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        await expect(page.locator('[data-testid="withdrawals-table"]')).toBeVisible();
    });

    test('status filter tabs are visible', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        await expect(page.locator('[data-testid="withdrawal-status-filters"]')).toBeVisible();
    });

    test('clicking Approved filter reloads with filtered view', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        const approvedFilter = page.locator('[data-testid="withdrawal-status-filters"]').locator('text=Approved');
        await approvedFilter.click();
        await page.waitForURL(/status=approved/, { timeout: 10000 });
        await expect(page.locator('[data-testid="withdrawals-table"]')).toBeVisible();
    });

    test('clicking Rejected filter reloads with filtered view', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        const rejectedFilter = page.locator('[data-testid="withdrawal-status-filters"]').locator('text=Rejected');
        await rejectedFilter.click();
        await page.waitForURL(/status=rejected/, { timeout: 10000 });
        await expect(page.locator('[data-testid="withdrawals-table"]')).toBeVisible();
    });

    test('can approve a pending withdrawal if one exists', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        const approveBtn = page.locator('[data-testid^="btn-approve-"]').first();
        if (await approveBtn.count() === 0) {
            test.skip();
            return;
        }
        const id = (await approveBtn.getAttribute('data-testid'))?.replace('btn-approve-', '');
        await approveBtn.click();
        await page.waitForLoadState('networkidle');
        // If AJAX failed (e.g. parallel test processed it first), reload to see actual state
        if (await page.locator(`[data-testid="withdrawal-row-${id}"]`).count() > 0) {
            await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        }
        await expect(page.locator(`[data-testid="btn-approve-${id}"]`)).not.toBeAttached({ timeout: 10000 });
    });

    test('can reject a pending withdrawal with a review note', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        const rejectBtn = page.locator('[data-testid^="btn-reject-"]').first();
        if (await rejectBtn.count() === 0) {
            test.skip();
            return;
        }
        const id = (await rejectBtn.getAttribute('data-testid'))?.replace('btn-reject-', '');
        const noteInput = page.locator(`[data-testid="input-review-note-${id}"]`);
        if (await noteInput.count() > 0) {
            await noteInput.fill('Insufficient bank details');
        }
        await rejectBtn.click();
        await page.waitForLoadState('networkidle');
        if (await page.locator(`[data-testid="withdrawal-row-${id}"]`).count() > 0) {
            await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        }
        await expect(page.locator(`[data-testid="btn-reject-${id}"]`)).not.toBeAttached({ timeout: 10000 });
    });

    test('FINANCE user can access withdrawals page', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        await expect(page.locator('[data-testid="withdrawals-table"]')).toBeVisible();
    });

    test('ADMIN user can access withdrawals page', async ({ page }) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        await expect(page.locator('[data-testid="withdrawals-table"]')).toBeVisible();
    });

    test('OPERATIONS user is blocked from withdrawals page', async ({ page }) => {
        await loginAs(page, OPERATIONS.mobile, OPERATIONS.password);
        await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        await expect(page.locator('[data-testid="withdrawals-table"]')).not.toBeVisible();
    });

    test('WFBO sidebar shows withdrawals nav link', async ({ page }) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo`, { waitUntil: 'networkidle' });
        await expect(page.locator('[data-testid="wfbo-sidebar"]')).toBeVisible();
        await expect(page.locator('[data-testid="wfbo-nav-withdrawals"]')).toBeVisible();
    });

    test('search form is visible on withdrawals page', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        await expect(page.locator('[data-testid="withdrawal-search-form"]')).toBeVisible();
        await expect(page.locator('[data-testid="input-withdrawal-search"]')).toBeVisible();
        await expect(page.locator('[data-testid="btn-withdrawal-search"]')).toBeVisible();
    });

    test('search input auto-submits via debounce without clicking Search', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        await page.waitForLoadState('networkidle');
        // Focus and type to ensure reliable input events
        await page.locator('[data-testid="input-withdrawal-search"]').focus();
        await page.keyboard.type('DebounceAutoTest', { delay: 50 });
        // Debounce fires at 400ms; wait for navigation/URL change
        await page.waitForURL(/search=DebounceAutoTest/, { timeout: 10000 });
        await expect(page.locator('[data-testid="withdrawals-table"]')).toBeVisible();
    });

    test('sidebar withdrawal badge element exists in DOM for FINANCE user', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        // Badge span is rendered server-side and managed by wfbo-pending controller
        await expect(page.locator('[data-wfbo-pending-target="withdrawalBadge"]')).toBeAttached();
    });

    test('searching by name filters the withdrawals table', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        await page.fill('[data-testid="input-withdrawal-search"]', 'Test');
        await page.click('[data-testid="btn-withdrawal-search"]');
        await page.waitForLoadState('networkidle');

        await expect(page.locator('[data-testid="withdrawals-table"]')).toBeVisible();
        expect(page.url()).toContain('search=Test');
    });

    test('searching by mobile number filters the withdrawals table', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        await page.fill('[data-testid="input-withdrawal-search"]', '+1000');
        await page.click('[data-testid="btn-withdrawal-search"]');
        await page.waitForLoadState('networkidle');

        await expect(page.locator('[data-testid="withdrawals-table"]')).toBeVisible();
        expect(page.url()).toContain('search=');
    });

    test('clear button removes search and reloads', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/withdrawals?search=Test`);
        await expect(page.locator('[data-testid="btn-withdrawal-search-clear"]')).toBeVisible();
        await page.click('[data-testid="btn-withdrawal-search-clear"]');
        await page.waitForLoadState('networkidle');

        expect(page.url()).not.toContain('search=');
        await expect(page.locator('[data-testid="withdrawals-table"]')).toBeVisible();
    });

    test('search preserves status filter', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/withdrawals?status=pending`);
        await page.fill('[data-testid="input-withdrawal-search"]', 'User');
        await page.click('[data-testid="btn-withdrawal-search"]');
        await page.waitForLoadState('networkidle');

        expect(page.url()).toContain('status=pending');
        expect(page.url()).toContain('search=User');
    });

    test('receipt view modal opens when View button is clicked', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/withdrawals`);
        const viewBtn = page.locator('[data-testid^="btn-view-receipt-"]').first();
        if (await viewBtn.count() === 0) {
            test.skip();
            return;
        }
        await viewBtn.click();
        await expect(page.locator('#receipt-modal')).toBeVisible();
    });

});
