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

test.describe('PX Employee Creates Tests', () => {
  test.setTimeout(120000);

  async function createObsInternal(page: Page): Promise<string> {
    await page.goto('/observations/create/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const titleInput = page.locator('input[name="title"]');
    if (await titleInput.count() > 0) {
      await titleInput.fill(`E2E Emp Obs ${Date.now()}`);
      await page.waitForTimeout(400);
    }
    await page.fill('textarea[name="description"]', `E2E employee observation test ${Date.now()}. Please ignore.`);
    await page.waitForTimeout(400);

    const dt = page.locator('input[name="incident_datetime"]');
    if (await dt.count() > 0) {
      const now = new Date();
      const p = (n: number) => String(n).padStart(2, '0');
      await dt.fill(`${now.getFullYear()}-${p(now.getMonth()+1)}-${p(now.getDate())}T${p(now.getHours())}:${p(now.getMinutes())}`);
      await page.waitForTimeout(400);
    }

    await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
    await page.waitForTimeout(800);
    await page.evaluate(() => {
      const f = document.getElementById('observationForm') as HTMLFormElement;
      if (f) f.submit();
    });
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(3000);

    const url = page.url();
    const m = url.match(/\/observations\/([0-9a-f-]+)\/?$/);
    return m ? m[1] : '';
  }

  test('create complaint via API', async ({ page }) => {
    const api = new ApiHelper(page);
    await api.authenticate('px_employee');
    const { response, body } = await api.createComplaint();
    expect(response.status()).toBeLessThan(400);
    expect(body?.id || body?.reference_number).toBeTruthy();
    await page.waitForTimeout(800);
  });

  test('create observation via internal form', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('px_employee');
    await page.waitForTimeout(800);

    const obsId = await createObsInternal(page);
    expect(obsId).toBeTruthy();
    await page.waitForTimeout(800);
  });

  test('create inquiry via internal form', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('px_employee');
    await page.waitForTimeout(800);

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

    const subjectField = page.locator('input[name="subject"], #id_subject');
    if (await subjectField.count() > 0) { await subjectField.fill(`E2E Emp Inquiry ${Date.now()}`); await page.waitForTimeout(400); }
    const msgField = page.locator('textarea[name="message"], #id_message');
    if (await msgField.count() > 0) { await msgField.fill(`E2E employee inquiry test ${Date.now()}. Please ignore.`); await page.waitForTimeout(400); }
    const categoryField = page.locator('select[name="category"], #id_category');
    if (await categoryField.count() > 0) { await categoryField.selectOption({ index: 1 }); await page.waitForTimeout(400); }

    await submitContentForm(page);

    const url = page.url();
    const ok = url.match(/\/inquiries\/[0-9a-f-]+\/?$/) || !url.includes('/new/');
    expect(ok).toBeTruthy();
    await page.waitForTimeout(800);
  });

  test('create suggestion via internal form', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('px_employee');
    await page.waitForTimeout(800);

    await page.goto('/suggestions/create/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

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

    const contactName = page.locator('input[name="contact_name"], #id_contact_name');
    if (await contactName.count() > 0) { await contactName.fill('E2E Test User'); await page.waitForTimeout(300); }
    const contactPhone = page.locator('input[name="contact_phone"], #id_contact_phone');
    if (await contactPhone.count() > 0) { await contactPhone.fill('0501112233'); await page.waitForTimeout(300); }
    const msgField = page.locator('textarea[name="message"], #id_message');
    if (await msgField.count() > 0) { await msgField.fill(`E2E employee suggestion test ${Date.now()}. Please ignore.`); await page.waitForTimeout(300); }
    const hospField = page.locator('select[name="hospital"], #id_hospital');
    if (await hospField.count() > 0) {
      const hasValue = await hospField.inputValue();
      if (!hasValue) { await hospField.selectOption(HOSPITAL_ID); await page.waitForTimeout(300); }
    }

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

  test('create appreciation via public API', async ({ page }) => {
    const resp = await page.request.post('/appreciation/public/submit/', {
      data: {
        contact_name: `E2E Test ${Date.now()}`,
        contact_phone: '0504445566',
        message: `E2E employee appreciation test ${Date.now()}. Great work!`,
        hospital: HOSPITAL_ID,
      },
    });
    expect([200, 201].includes(resp.status())).toBeTruthy();
    await page.waitForTimeout(800);
  });

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

    await page.goto('/projects/create/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

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

    const nameField = page.locator('input[name="name"], #id_name');
    if (await nameField.count() > 0) { await nameField.fill(`E2E QI Project ${Date.now()}`); await page.waitForTimeout(400); }
    const descField = page.locator('textarea[name="description"], #id_description');
    if (await descField.count() > 0) { await descField.fill(`E2E QI project test ${Date.now()}. Please ignore.`); await page.waitForTimeout(400); }

    await submitContentForm(page);

    const url = page.url();
    const ok = url.match(/\/projects\/[0-9a-f-]+\/?$/) || !url.includes('/create/');
    expect(ok).toBeTruthy();
    await page.waitForTimeout(800);
  });
});
