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

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

  test.describe('Public Complaint Form', () => {
    test('submit complaint via landing page', async ({ page }) => {
      const pub = new PublicFormHelper(page);
      await pub.goToPublicLanding();
      await page.waitForTimeout(2000);

      await pub.selectFormType('complaint');
      await page.waitForTimeout(2000);

      await page.selectOption('#id_hospital', HOSPITAL_ID);
      await page.waitForTimeout(1000);

      await page.selectOption('#id_location', '49');
      await page.waitForTimeout(1500);

      const sectionOpts = await page.locator('#id_main_section option').count();
      if (sectionOpts > 1) {
        await page.selectOption('#id_main_section', { index: 1 });
        await page.waitForTimeout(1000);
      }

      await page.fill('#id_complainant_name', `E2E Test User ${Date.now()}`);
      await page.fill('#id_mobile_number', '0501234567');
      await page.selectOption('#id_relation_to_patient', 'patient');
      await page.fill('#id_complaint_details', `E2E public complaint test ${Date.now()}. Please ignore. This is an automated test.`);
      await page.waitForTimeout(1200);

      await page.click('#submit_btn');
      await page.waitForLoadState('domcontentloaded');
      await page.waitForTimeout(4000);

      const url = page.url();
      const bodyText = (await page.textContent('body')) || '';
      const ok = url.includes('success') || url.includes('CMP-') || bodyText.includes('CMP-') || bodyText.includes('success');
      expect(ok).toBeTruthy();
      await page.waitForTimeout(800);
    });
  });

  test.describe('Public Inquiry Form', () => {
    test('submit inquiry via landing page', async ({ page }) => {
      const pub = new PublicFormHelper(page);
      await pub.goToPublicLanding();
      await page.waitForTimeout(2000);

      await pub.selectFormType('inquiry');
      await page.waitForTimeout(3000);

      const nameInput = page.locator('#inquiryForm input[name="name"]');
      await nameInput.fill(`E2E Inquiry User ${Date.now()}`);
      await page.waitForTimeout(400);

      const phoneInput = page.locator('#inquiryForm input[name="phone"]');
      await phoneInput.fill('0509876543');
      await page.waitForTimeout(400);

      const msgInput = page.locator('#inquiryForm textarea[name="message"]');
      await msgInput.fill(`E2E public inquiry test ${Date.now()}. Please ignore.`);
      await page.waitForTimeout(400);

      const hospSelect = page.locator('#inquiryForm select[name="hospital"]');
      await hospSelect.selectOption(HOSPITAL_ID);
      await page.waitForTimeout(1200);

      const submitBtn = page.locator('#inqSubmitBtn');
      await submitBtn.click();
      await page.waitForTimeout(4000);

      const bodyText = (await page.textContent('body')) || '';
      const ok = bodyText.includes('INQ-') || bodyText.includes('success') || bodyText.includes('Successfully');
      expect(ok).toBeTruthy();
      await page.waitForTimeout(800);
    });
  });

  test.describe('Public Observation Form', () => {
    test('submit observation via API endpoint', async ({ page }) => {
      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 resp = await page.request.post('/core/public/observation/submit/', {
        form: {
          description: `E2E public observation test ${Date.now()}. Please ignore.`,
          hospital: HOSPITAL_ID,
          severity: 'low',
          csrfmiddlewaretoken: csrf,
        },
        headers: csrf ? { 'X-CSRFToken': csrf, Referer: 'http://localhost:8000/' } : {},
      });
      expect([200, 201].includes(resp.status())).toBeTruthy();
      const body = await resp.json().catch(() => null);
      if (body) {
        expect(body.tracking_code || body.reference || body.success || body.message).toBeTruthy();
      }
    });
  });

  test.describe('Public Suggestion Form', () => {
    test('submit suggestion via API', async ({ page }) => {
      const resp = await page.request.post('/suggestions/public/suggestion/', {
        data: {
          contact_name: `E2E Test ${Date.now()}`,
          contact_phone: '0501112233',
          message: `E2E public suggestion test ${Date.now()}. Please ignore.`,
          hospital: HOSPITAL_ID,
          category: 'general',
        },
      });
      expect([200, 201].includes(resp.status())).toBeTruthy();
      const body = await resp.json().catch(() => null);
      if (body) {
        expect(body.reference || body.id || body.success || body.message).toBeTruthy();
      }
    });
  });

  test.describe('Public Appreciation Form', () => {
    test('submit appreciation via API', async ({ page }) => {
      const resp = await page.request.post('/appreciation/public/submit/', {
        data: {
          contact_name: `E2E Test ${Date.now()}`,
          contact_phone: '0504445566',
          message: `E2E public appreciation test ${Date.now()}. Thank you for great service!`,
          hospital: HOSPITAL_ID,
        },
      });
      expect([200, 201].includes(resp.status())).toBeTruthy();
      const body = await resp.json().catch(() => null);
      if (body) {
        expect(body.reference || body.id || body.success || body.message).toBeTruthy();
      }
    });
  });
});
