import { test, expect } from '@playwright/test';
import { RoleAuthHelper } from '../../helpers/helpers';

test.describe('Inquiry Lifecycle', () => {
  test.describe.configure({ mode: 'serial' });

  let inquiryReference = '';

  test('submit inquiry via public form', async ({ page }) => {
    await page.goto('/inquiries/public/submit/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(1000);

    const timestamp = Date.now();
    const nameInput = page.locator('input[name="name"], #inquiry_name');
    if (await nameInput.count() > 0) {
      await nameInput.fill(`E2E Inquiry ${timestamp}`);
    }
    const emailInput = page.locator('input[name="email"], #inquiry_email');
    if (await emailInput.count() > 0) {
      await emailInput.fill(`e2e-inquiry-${timestamp}@test.com`);
    }
    const phoneInput = page.locator('input[name="phone"], #inquiry_phone');
    if (await phoneInput.count() > 0) {
      await phoneInput.fill('0559876543');
    }
    const hospitalSelect = page.locator('select[name="hospital"], #inquiry_hospital');
    if (await hospitalSelect.count() > 0) {
      await hospitalSelect.selectOption({ index: 0 });
    }
    const categorySelect = page.locator('select[name="category"], #inquiry_category');
    if (await categorySelect.count() > 0) {
      await categorySelect.selectOption({ index: 0 });
    }
    const subjectInput = page.locator('input[name="subject"], #inquiry_subject');
    if (await subjectInput.count() > 0) {
      await subjectInput.fill(`E2E Test Inquiry ${timestamp}`);
    }
    const messageInput = page.locator('textarea[name="message"], #inquiry_message');
    if (await messageInput.count() > 0) {
      await messageInput.fill('E2E automated test inquiry - please ignore');
    }

    const submitBtn = page.locator('button[type="submit"], #inquirySubmitBtn');
    await submitBtn.click();
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(3000);

    const pageText = await page.textContent('body');
    const match = pageText?.match(/INQ-\d{8}-\d{6}/);
    if (match) {
      inquiryReference = match[0];
    }

    const success = pageText?.includes('success') || pageText?.includes('thank') || pageText?.includes('received') || !!match;
    expect(success).toBeTruthy();
  });

  test('inquiry appears in admin list', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');

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

    if (inquiryReference) {
      const searchInput = page.locator('input[name="search"]');
      if (await searchInput.count() > 0) {
        await searchInput.fill(inquiryReference);
        await searchInput.press('Enter');
        await page.waitForLoadState('domcontentloaded');
        await page.waitForTimeout(1000);
      }

      const tableText = await page.locator('table').textContent();
      expect(tableText).toContain(inquiryReference);
    } else {
      const tableText = await page.locator('table').textContent();
      expect(tableText).toBeTruthy();
    }
  });

  test('inquiry list has filter and table', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');

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

    const table = page.locator('table.data-table, table');
    expect(await table.count()).toBeGreaterThan(0);

    const filterForm = page.locator('form[method="get"]');
    expect(await filterForm.count()).toBeGreaterThan(0);
  });

  test('can access inquiry create form (authenticated)', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');

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

    const form = page.locator('#inquiryForm, form[action*="inquiry_create"]');
    const hasForm = await form.count().then(c => c > 0);
    expect(hasForm).toBeTruthy();
  });

  test('inquiry detail page loads for open inquiry', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');

    await page.goto('/inquiries/?status=open');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2000);

    const firstRow = page.locator('table tbody tr').first();
    const hasRows = await firstRow.count().then(c => c > 0);
    if (!hasRows) {
      test.skip();
      return;
    }

    await firstRow.click();
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(1000);

    const pageText = await page.textContent('body');
    expect(pageText).toContain('INQ-');
  });

  test('respond modal opens on inquiry detail', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');

    await page.goto('/inquiries/?status=open');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2000);

    const firstRow = page.locator('table tbody tr').first();
    const hasRows = await firstRow.count().then(c => c > 0);
    if (!hasRows) {
      test.skip();
      return;
    }

    await firstRow.click();
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(1000);

    const respondBtn = page.locator('button[onclick="showRespondModal()"]');
    const hasRespond = await respondBtn.count().then(c => c > 0);
    if (!hasRespond) {
      test.skip();
      return;
    }

    await respondBtn.click();
    const modal = page.locator('#respondModal');
    await modal.waitFor({ state: 'visible', timeout: 5000 });

    const form = modal.locator('form#respondForm, form[action*="respond"]');
    expect(await form.count()).toBeGreaterThan(0);

    const closeBtn = modal.locator('button[onclick="closeRespondModal()"]');
    if (await closeBtn.count() > 0) {
      await closeBtn.click();
    }
  });

  test('inquiry list shows status badges', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');

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

    const statusBadges = page.locator('span.rounded-full');
    const badgeCount = await statusBadges.count();
    expect(badgeCount).toBeGreaterThan(0);
  });
});
