import { test, expect } from '@playwright/test';
import { RoleAuthHelper, submitContentForm } from '../../helpers/helpers';
import { HOSPITAL_ID } from '../../helpers/api-helper';

test.describe('PX Source Workflow Tests', () => {
  test.setTimeout(120000);
  test.describe.configure({ mode: 'serial' });

  let sourceId: string;

  test('create PX source', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');
    await page.waitForTimeout(800);

    await page.goto('/px-sources/new/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const pageText = (await page.textContent('body')) || '';
    if (pageText.includes('404') || pageText.includes('403')) {
      test.skip();
      return;
    }

    await page.locator('input[name="name_en"]').fill(`E2E Test Source ${Date.now()}`);
    await page.waitForTimeout(300);
    await page.locator('input[name="code"]').fill(`E2E-${Date.now()}`);
    await page.waitForTimeout(300);
    await page.locator('input[name="contact_email"]').fill('e2e-source-test@px360.test');
    await page.waitForTimeout(300);

    await submitContentForm(page);

    const url = page.url();
    const m = url.match(/\/px-sources\/([0-9a-f-]+)\/?$/);
    sourceId = m ? m[1] : '';
    expect(url).not.toContain('/new/');
    await page.waitForTimeout(800);
  });

  test('assign user to source', async ({ page }) => {
    if (!sourceId) { test.skip(); return; }

    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');
    await page.waitForTimeout(800);

    await page.goto(`/px-sources/${sourceId}/users/create/`);
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    await page.locator('input[name="email"]').fill(`e2e-source-test-${Date.now()}@px360.test`);
    await page.waitForTimeout(300);
    await page.locator('input[name="first_name"]').fill('E2E');
    await page.waitForTimeout(300);
    await page.locator('input[name="last_name"]').fill('SourceTest');
    await page.waitForTimeout(300);

    await submitContentForm(page);
    expect(page.url()).not.toContain('/users/create');
    await page.waitForTimeout(800);
  });

  test('login as source user and access dashboard', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('source_user');
    await page.waitForTimeout(800);

    await page.waitForURL(/\/px-sources\/dashboard/, { timeout: 10000 }).catch(() => {});
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    expect(page.url()).toContain('/px-sources/');
    await page.waitForTimeout(800);
  });

  test('source user creates complaint', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('source_user');
    await page.waitForTimeout(800);

    await page.goto('/px-sources/complaints/new/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const fields: [string, string][] = [
      ['complainant_name', `E2E Source User ${Date.now()}`],
      ['mobile_number', '0509998877'],
      ['patient_name', `E2E Patient ${Date.now()}`],
      ['national_id', `E2E${Date.now()}`.substring(0, 20)],
      ['complaint_details', `E2E source complaint test ${Date.now()}. Please ignore.`],
    ];
    for (const [name, value] of fields) {
      const f = page.locator(`input[name="${name}"], textarea[name="${name}"]`);
      if (await f.count() > 0) { await f.fill(value); await page.waitForTimeout(200); }
    }
    const relField = page.locator('select[name="relation_to_patient"]');
    if (await relField.count() > 0) await relField.selectOption('patient');
    const dateField = page.locator('input[name="incident_date"]');
    if (await dateField.count() > 0) {
      const now = new Date();
      const p = (n: number) => String(n).padStart(2, '0');
      await dateField.fill(`${now.getFullYear()}-${p(now.getMonth()+1)}-${p(now.getDate())}`);
    }

    await submitContentForm(page);
    expect(page.url()).not.toContain('/complaints/new');
    await page.waitForTimeout(800);
  });

  test('source user creates inquiry', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('source_user');
    await page.waitForTimeout(800);

    await page.goto('/px-sources/inquiries/new/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const subjectField = page.locator('input[name="subject"]');
    if (await subjectField.count() > 0) await subjectField.fill(`E2E Source Inquiry ${Date.now()}`);
    const msgField = page.locator('textarea[name="message"]');
    if (await msgField.count() > 0) await msgField.fill(`E2E source inquiry test ${Date.now()}. Please ignore.`);

    await submitContentForm(page);
    expect(page.url()).not.toContain('/inquiries/new');
    await page.waitForTimeout(800);
  });

  test('source user creates observation', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('source_user');
    await page.waitForTimeout(800);

    await page.goto('/px-sources/observations/new/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const descField = page.locator('textarea[name="description"]');
    if (await descField.count() > 0) await descField.fill(`E2E source observation test ${Date.now()}. Please ignore.`);

    await submitContentForm(page);
    expect(page.url()).not.toContain('/observations/new');
    await page.waitForTimeout(800);
  });

  test('source user creates suggestion', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('source_user');
    await page.waitForTimeout(800);

    await page.goto('/px-sources/suggestions/new/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const msgField = page.locator('textarea[name="message"]');
    if (await msgField.count() > 0) await msgField.fill(`E2E source suggestion test ${Date.now()}. Please ignore.`);

    await submitContentForm(page);
    expect(page.url()).not.toContain('/suggestions/new');
    await page.waitForTimeout(800);
  });
});
