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

test.describe('WFBO Payment Details', () => {

    test.describe('access control', () => {

        test('admin can access payment details page', async ({ page }) => {
            await loginAs(page, ADMIN.mobile, ADMIN.password);
            await page.goto(`${BASE_URL}/wfbo/payment-details`);

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

        test('regular user cannot access WFBO payment details', async ({ page }) => {
            await loginAs(page, USER.mobile, USER.password);
            await page.goto(`${BASE_URL}/wfbo/payment-details`);

            await expect(page.locator('[data-testid="wfbo-sidebar"]')).not.toBeVisible();
        });

        test('agent cannot access WFBO payment details', async ({ page }) => {
            await loginAs(page, AGENT.mobile, AGENT.password);
            await page.goto(`${BASE_URL}/wfbo/payment-details`);

            await expect(page.locator('[data-testid="wfbo-sidebar"]')).not.toBeVisible();
        });

        test('unauthenticated user is redirected away from payment details', async ({ page }) => {
            await page.context().clearCookies();
            await page.goto(`${BASE_URL}/wfbo/payment-details`);

            expect(page.url()).not.toContain('/wfbo/payment-details');
        });

    });

    test.describe('CRUD as admin', () => {

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

        test('payment details page loads with Add New button', async ({ page }) => {
            await page.goto(`${BASE_URL}/wfbo/payment-details`);

            await expect(page.locator('[data-testid="wfbo-sidebar"]')).toBeVisible();
            await expect(page.locator('[data-testid="btn-new-payment-detail"]')).toBeVisible();
        });

        test('new payment detail form loads', async ({ page }) => {
            await page.goto(`${BASE_URL}/wfbo/payment-details/new`);

            await expect(page.locator('[data-testid="payment-detail-form"]')).toBeVisible();
            await expect(page.locator('[data-testid="input-label"]')).toBeVisible();
            await expect(page.locator('[data-testid="input-bank-name"]')).toBeVisible();
            await expect(page.locator('[data-testid="input-account-name"]')).toBeVisible();
            await expect(page.locator('[data-testid="input-account-number"]')).toBeVisible();
            await expect(page.locator('[data-testid="btn-submit"]')).toBeVisible();
            const handler = page.locator('[data-testid="select-finance-handler"]');
            await expect(handler).toBeVisible();
            await expect(handler.locator('option', { hasText: 'Unassigned' })).toHaveCount(1);
        });

        test('can create a new payment detail', async ({ page }) => {
            const label = `Test Bank ${Date.now()}`;

            await page.goto(`${BASE_URL}/wfbo/payment-details/new`);
            await page.fill('[data-testid="input-label"]', label);
            await page.fill('[data-testid="input-bank-name"]', 'BDO');
            await page.fill('[data-testid="input-account-name"]', 'Test Account');
            await page.fill('[data-testid="input-account-number"]', '1234567890');
            await page.click('[data-testid="btn-submit"]');

            await expect(page).toHaveURL(`${BASE_URL}/wfbo/payment-details`);
            await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();
            await expect(page.locator('[data-testid="payment-details-table"]')).toBeVisible();
            // Left unassigned -> handler column shows a dash.
            await expect(page.locator('[data-testid^="handler-"]').last()).toHaveText('—');
        });

        test('submitting empty form shows errors', async ({ page }) => {
            await page.goto(`${BASE_URL}/wfbo/payment-details/new`);
            await page.click('[data-testid="btn-submit"]');

            await expect(page).toHaveURL(`${BASE_URL}/wfbo/payment-details/new`);
            await expect(page.locator('[data-testid="flash-error"]').first()).toBeVisible();
        });

        test('can edit an existing payment detail', async ({ page }) => {
            // Create one first
            const label = `Edit Test ${Date.now()}`;
            await page.goto(`${BASE_URL}/wfbo/payment-details/new`);
            await page.fill('[data-testid="input-label"]', label);
            await page.fill('[data-testid="input-bank-name"]', 'BDO');
            await page.fill('[data-testid="input-account-name"]', 'Original Name');
            await page.fill('[data-testid="input-account-number"]', '0000000001');
            await page.click('[data-testid="btn-submit"]');

            await expect(page).toHaveURL(`${BASE_URL}/wfbo/payment-details`);

            // Find the edit button for the newly created row
            const editBtn = page.locator('[data-testid^="btn-edit-"]').last();
            if (await editBtn.count() === 0) {
                test.skip();
                return;
            }

            await editBtn.click();
            await expect(page.locator('[data-testid="payment-detail-form"]')).toBeVisible();

            await page.fill('[data-testid="input-account-name"]', 'Updated Name');
            await page.click('[data-testid="btn-submit"]');

            await expect(page).toHaveURL(`${BASE_URL}/wfbo/payment-details`);
            await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();
        });

        test('can delete a payment detail', async ({ page }) => {
            // Create one first so we have something to delete
            const label = `Delete Test ${Date.now()}`;
            await page.goto(`${BASE_URL}/wfbo/payment-details/new`);
            await page.fill('[data-testid="input-label"]', label);
            await page.fill('[data-testid="input-bank-name"]', 'Delete Bank');
            await page.fill('[data-testid="input-account-name"]', 'Delete Name');
            await page.fill('[data-testid="input-account-number"]', '9999999999');
            await page.click('[data-testid="btn-submit"]');

            await expect(page).toHaveURL(`${BASE_URL}/wfbo/payment-details`);

            const deleteBtn = page.locator('[data-testid^="btn-delete-"]').last();
            if (await deleteBtn.count() === 0) {
                test.skip();
                return;
            }

            // Accept the confirm dialog
            page.once('dialog', dialog => dialog.accept());
            await deleteBtn.click();

            await expect(page).toHaveURL(`${BASE_URL}/wfbo/payment-details`);
            await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();
        });

        test('WFBO sidebar has payment details nav link', async ({ page }) => {
            await page.goto(`${BASE_URL}/wfbo/payment-details`);

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

    });

    test.describe('disabled bank still selectable on deposit form', () => {

        test('a disabled payment detail moves to "Others" instead of disappearing', async ({ page }) => {
            const label = `Disable Test ${Date.now()}`;

            await loginAs(page, ADMIN.mobile, ADMIN.password);
            await page.goto(`${BASE_URL}/wfbo/payment-details/new`);
            await page.fill('[data-testid="input-label"]', label);
            await page.fill('[data-testid="input-bank-name"]', 'Soon Inactive Bank');
            await page.fill('[data-testid="input-account-name"]', 'Test Account');
            await page.fill('[data-testid="input-account-number"]', `${Date.now()}`.slice(-10));
            await page.click('[data-testid="btn-submit"]');
            await expect(page).toHaveURL(`${BASE_URL}/wfbo/payment-details`);

            const row = page.locator('[data-testid^="payment-detail-row-"]').filter({ hasText: 'Soon Inactive Bank' }).last();
            const toggleBtn = row.locator('[data-testid^="btn-toggle-"]');
            const toggleTestId = await toggleBtn.getAttribute('data-testid');
            const detailId = toggleTestId?.replace('btn-toggle-', '');
            if (!detailId) {
                test.skip();
                return;
            }

            page.once('dialog', dialog => dialog.accept());
            await toggleBtn.click();
            await expect(page.locator(`[data-testid="badge-status-${detailId}"]`)).toHaveText('Disabled');

            await loginAs(page, USER.mobile, USER.password);
            await page.goto(`${BASE_URL}/deposit`);

            // Absent from the primary "send to" dropdown and the info panel...
            await expect(page.locator(`[data-testid="select-payment-detail"] option[value="${detailId}"]`)).toHaveCount(0);
            await expect(page.locator(`[data-testid="payment-detail-${detailId}"]`)).toHaveCount(0);

            // ...but still selectable under "Others".
            await page.selectOption('[data-testid="select-payment-detail"]', 'others');
            const otherOption = page.locator(`[data-testid="select-payment-detail-other"] option[value="${detailId}"]`);
            await expect(otherOption).toHaveCount(1);
            await expect(otherOption).toHaveText(/Soon Inactive Bank/);

            await page.selectOption('[data-testid="select-payment-detail-other"]', detailId);
            await page.fill('[data-testid="input-amount"]', '100.00');
            await page.fill('[data-testid="input-transaction-reference"]', `TXN-OTHERS-${Date.now()}`);
            await page.click('[data-testid="btn-deposit-submit"]');

            await expect(page).toHaveURL(`${BASE_URL}/deposit`);
            await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();
        });

    });

});
