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

test.describe('Public Tracking Tests', () => {
  test.setTimeout(120000);

  test.describe.configure({ mode: 'serial' });

  let complaintRef: string;
  let inquiryRef: string;
  let observationCode: string;

  test('create entities for tracking', async ({ page }) => {
    const api = new ApiHelper(page);
    await api.authenticate('px_admin');

    const { response: cr, body: cb } = await api.createComplaint();
    expect(cr.status()).toBe(201);
    complaintRef = cb?.reference_number || '';

    const { response: ir, body: ib } = await api.createInquiry();
    expect(ir.status()).toBe(201);
    inquiryRef = ib?.reference_number || '';

    await page.goto('/core/public/submit/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(1500);
    const csrfCookie = await page.context().cookies();
    const csrf = csrfCookie.find(c => c.name === 'csrftoken')?.value || '';
    const obsResp = await page.request.post('/core/public/observation/submit/', {
      form: {
        description: `E2E tracking obs ${Date.now()}`,
        hospital: HOSPITAL_ID,
        severity: 'low',
        csrfmiddlewaretoken: csrf,
      },
      headers: csrf ? { 'X-CSRFToken': csrf, Referer: 'http://localhost:8000/' } : {},
    });
    const obsBody = await obsResp.json().catch(() => null);
    observationCode = obsBody?.tracking_code || obsBody?.reference || '';
    expect(obsResp.status()).toBeLessThan(400);
  });

  test('track complaint via unified tracking page', async ({ page }) => {
    if (!complaintRef) { test.skip(); return; }

    await page.goto('/core/public/track/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    await page.click('[data-type="complaint"], .track-card:has-text("Complaint")').catch(() => {});
    await page.waitForTimeout(800);

    const refInput = page.locator('input[name="reference"], input[name="tracking_code"], #trackReference');
    if (await refInput.count() > 0) {
      await refInput.first().fill(complaintRef);
      await page.waitForTimeout(600);
      await page.click('button[type="submit"], .track-btn').catch(() => {});
      await page.waitForLoadState('domcontentloaded');
      await page.waitForTimeout(3000);

      const pageText = (await page.textContent('body')) || '';
      expect(pageText).toContain(complaintRef);
    }
    await page.waitForTimeout(800);
  });

  test('track complaint via standalone tracking page', async ({ page }) => {
    if (!complaintRef) { test.skip(); return; }

    await page.goto('/complaints/public/track/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const refInput = page.locator('input[name="reference_number"]');
    if (await refInput.count() > 0) {
      await refInput.fill(complaintRef);
      await page.waitForTimeout(600);
      await page.click('button[type="submit"]');
      await page.waitForLoadState('domcontentloaded');
      await page.waitForTimeout(3000);

      const pageText = (await page.textContent('body')) || '';
      expect(pageText).toContain(complaintRef);
    }
    await page.waitForTimeout(800);
  });

  test('track inquiry via standalone tracking page', async ({ page }) => {
    if (!inquiryRef) { test.skip(); return; }

    await page.goto('/inquiries/public/track/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const refInput = page.locator('input[name="reference_number"]');
    if (await refInput.count() > 0) {
      await refInput.fill(inquiryRef);
      await page.waitForTimeout(600);
      await page.click('button[type="submit"]');
      await page.waitForLoadState('domcontentloaded');
      await page.waitForTimeout(3000);

      const pageText = (await page.textContent('body')) || '';
      expect(pageText).toContain(inquiryRef);
    }
    await page.waitForTimeout(800);
  });

  test('track observation via standalone tracking page', async ({ page }) => {
    if (!observationCode) { test.skip(); return; }

    await page.goto('/observations/track/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const codeInput = page.locator('input[name="tracking_code"]');
    if (await codeInput.count() > 0) {
      await codeInput.fill(observationCode);
      await page.waitForTimeout(600);
      await page.click('button[type="submit"]');
      await page.waitForLoadState('domcontentloaded');
      await page.waitForTimeout(3000);

      const pageText = (await page.textContent('body')) || '';
      expect(pageText).toContain(observationCode);
    }
    await page.waitForTimeout(800);
  });
});
