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

test.describe('Authentication - Login Page', () => {
  test('login page loads with form fields', async ({ page }) => {
    await page.goto('/accounts/login/');
    await page.waitForSelector('#email');
    await expect(page.locator('#email')).toBeVisible();
    await expect(page.locator('#password')).toBeVisible();
    await expect(page.locator('button[type="submit"]')).toBeVisible();
    await expect(page.locator('h1')).toContainText('Welcome to PX360');
  });

  test('login with empty fields shows validation', async ({ page }) => {
    await page.goto('/accounts/login/');
    await page.waitForSelector('#email');

    await page.click('button[type="submit"]');

    const emailRequired = await page.locator('#email:invalid').count();
    const passwordRequired = await page.locator('#password:invalid').count();

    expect(emailRequired + passwordRequired).toBeGreaterThan(0);
  });

  test('password visibility toggle works', async ({ page }) => {
    await page.goto('/accounts/login/');
    await page.waitForSelector('#password');

    const passwordField = page.locator('#password');
    await expect(passwordField).toHaveAttribute('type', 'password');

    await page.click('#togglePassword');
    await expect(passwordField).toHaveAttribute('type', 'text');

    await page.click('#togglePassword');
    await expect(passwordField).toHaveAttribute('type', 'password');
  });

  test('forgot password link navigates to reset page', async ({ page }) => {
    await page.goto('/accounts/login/');
    await page.waitForSelector('#email');

    await page.click('a:has-text("Forgot password")');

    await page.waitForURL(/\/accounts\/password\/reset\/?/, { timeout: 10000 });
    await expect(page.locator('#id_email')).toBeVisible();
  });

  test('failed login with invalid credentials shows error', async ({ page }) => {
    await page.goto('/accounts/login/');
    await page.waitForSelector('#email');

    await page.fill('#email', 'invalid@example.com');
    await page.fill('#password', 'wrongpassword');
    await page.click('button[type="submit"]');

    await page.waitForLoadState('domcontentloaded');

    const hasError = await page.locator('.bg-red-50, [role="alert"]').count().then(c => c > 0);
    const stillOnLogin = page.url().includes('login');

    expect(hasError || stillOnLogin).toBeTruthy();
  });
});

test.describe('Authentication - Login with Credentials', () => {
  test('successful login with valid PX Admin credentials', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('px_admin');

    expect(page.url()).not.toContain('login');
  });

  test('successful login with valid Hospital Admin credentials', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');

    expect(page.url()).not.toContain('login');
    expect(page.url()).not.toContain('select-hospital');
  });
});

test.describe('Authentication - Logout', () => {
  test('logout redirects to login page', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('px_admin');
    await auth.logout();

    await page.waitForURL(/\/accounts\/login\/?/, { timeout: 10000 });
    await expect(page.locator('#email')).toBeVisible();
  });
});

test.describe('Authentication - Password Reset', () => {
  test('password reset form submits with email', async ({ page }) => {
    await page.goto('/accounts/password/reset/');
    await page.waitForSelector('#id_email');

    await page.fill('#id_email', 'e2e-px-admin@px360.test');
    await page.click('button[type="submit"]');
    await page.waitForLoadState('domcontentloaded');

    const hasSuccess = await page.locator('.bg-green-50').count().then(c => c > 0);
    expect(hasSuccess).toBeTruthy();
  });

  test('password reset back to login link works', async ({ page }) => {
    await page.goto('/accounts/password/reset/');
    await page.waitForSelector('#id_email');

    await page.click('a:has-text("Back to Login")');

    await page.waitForURL(/\/accounts\/login\/?/, { timeout: 10000 });
    await expect(page.locator('#email')).toBeVisible();
  });
});

test.describe('Authentication - Hospital Selection', () => {
  test('hospital select page loads for PX Admin user', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('px_admin');

    const url = page.url();
    if (url.includes('select-hospital')) {
      await page.waitForSelector('.hospital-card, .bg-amber-50', { timeout: 10000 });
      const hasHospitals = await page.locator('.hospital-card').count().then(c => c > 0);
      const hasEmptyState = await page.locator('.bg-amber-50').count().then(c => c > 0);
      expect(hasHospitals || hasEmptyState).toBeTruthy();
    } else {
      expect(url).toContain('localhost');
    }
  });

  test('selecting a hospital redirects to dashboard', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('px_admin');

    const url = page.url();
    if (!url.includes('select-hospital')) return;

    const hospitalCard = page.locator('.hospital-card').first();
    const hasCards = await hospitalCard.count().then(c => c > 0);
    if (!hasCards) return;

    await hospitalCard.click();

    const selected = await page.locator('.hospital-card.selected').count().then(c => c > 0);
    if (selected) {
      await page.click('button[type="submit"]');
      await page.waitForLoadState('domcontentloaded');
      expect(page.url()).not.toContain('select-hospital');
    }
  });
});
