import { test, expect } from '@playwright/test'
import { AuthHelper, generateTestEmail, generateTestPassword, TEST_LANGUAGE } from '../helpers/auth'
import { createMailpitHelper } from '../helpers/mailpit'

test.describe('Security Page', () => {
  let testEmail: string
  let testPassword: string

  test.beforeEach(async ({ page, request }) => {
    // Clean Mailpit inbox before each test
    const mailpit = createMailpitHelper(request)
    await mailpit.deleteAllMessages()

    // Create unique test user for each test
    testEmail = generateTestEmail('security')
    testPassword = generateTestPassword()

    const auth = new AuthHelper(page)

    // 1. Register the user
    await auth.register(testEmail, testPassword, 'Security Test User')
    await page.waitForLoadState('networkidle')

    // 2. Wait for verification email and get verification link
    const verificationEmail = await mailpit.waitForEmail(testEmail, {
      subject: /verify/i,
      timeout: 10000
    })
    const verificationLink = await mailpit.getVerificationLink(verificationEmail.ID)

    if (!verificationLink) {
      throw new Error('No verification link found in email')
    }

    // 3. Click verification link
    await page.goto(verificationLink)
    await page.waitForLoadState('networkidle')

    // 4. User should now be verified and logged in automatically
    // Wait for redirect to dashboard (autoSignInAfterVerification: true)
    await page.waitForURL('**/dashboard**', { timeout: 10000 })
  })

  test('renders security page for authenticated users', async ({ page }) => {
    await page.goto('/dashboard/account/security')
    await page.waitForLoadState('networkidle')

    // Should see the security page
    expect(page.url()).toContain('/dashboard/account/security')
  })

  test('renders password change form when authenticated', async ({ page }) => {
    await page.goto('/dashboard/account/security')
    await page.waitForLoadState('networkidle')

    // Check for heading using Dutch translation
    await expect(page.getByText('Wachtwoord Wijzigen').first()).toBeVisible()

    // Check for password inputs using getByLabel with Dutch labels (exact match)
    await expect(page.getByLabel('Huidig Wachtwoord', { exact: true })).toBeVisible()
    await expect(page.getByLabel('Nieuw Wachtwoord', { exact: true })).toBeVisible()
    await expect(page.getByLabel('Bevestig Nieuw Wachtwoord', { exact: true })).toBeVisible()
  })

  test('shows validation error for mismatched passwords', async ({ page }) => {
    await page.goto('/dashboard/account/security')
    await page.waitForLoadState('networkidle')

    await page.getByLabel('Huidig Wachtwoord', { exact: true }).fill('CurrentPass123!')
    await page.getByLabel('Nieuw Wachtwoord', { exact: true }).fill('NewPass123!')
    await page.getByLabel('Bevestig Nieuw Wachtwoord', { exact: true }).fill('DifferentPass456!')

    // Should show validation error
    await expect(
      page.getByText(TEST_LANGUAGE.passwordsDoNotMatch)
    ).toBeVisible()
  })

  test('shows validation error for short password', async ({ page }) => {
    await page.goto('/dashboard/account/security')
    await page.waitForLoadState('networkidle')

    await page.getByLabel('Nieuw Wachtwoord', { exact: true }).fill('Short1!')

    // Should show minimum length error (appears twice: as hint and as error, use first())
    await expect(
      page.getByText(TEST_LANGUAGE.passwordMinLength).first()
    ).toBeVisible()
  })

  test('reset button clears all fields', async ({ page }) => {
    await page.goto('/dashboard/account/security')
    await page.waitForLoadState('networkidle')

    // Fill all fields
    await page.getByLabel('Huidig Wachtwoord', { exact: true }).fill('test')
    await page.getByLabel('Nieuw Wachtwoord', { exact: true }).fill('test')
    await page.getByLabel('Bevestig Nieuw Wachtwoord', { exact: true }).fill('test')

    // Click reset button (using Dutch translation)
    await page.getByRole('button', { name: 'Herstellen' }).click()

    // Fields should be empty
    await expect(page.getByLabel('Huidig Wachtwoord', { exact: true })).toHaveValue('')
    await expect(page.getByLabel('Nieuw Wachtwoord', { exact: true })).toHaveValue('')
    await expect(page.getByLabel('Bevestig Nieuw Wachtwoord', { exact: true })).toHaveValue('')
  })

  test('displays passkey section', async ({ page }) => {
    await page.goto('/dashboard/account/security')
    await page.waitForLoadState('networkidle')

    // Check for Passkeys heading
    await expect(page.getByText('Passkeys').first()).toBeVisible()

    // Check for Add Passkey button (using Dutch translation)
    await expect(page.getByRole('button', { name: 'Passkey Toevoegen' })).toBeVisible()
  })

  test('submit button disabled until all fields valid', async ({ page }) => {
    await page.goto('/dashboard/account/security')
    await page.waitForLoadState('networkidle')

    // Get submit button (using Dutch translation)
    const submitButton = page.getByRole('button', { name: 'Wachtwoord Bijwerken' })

    // Should be disabled initially
    await expect(submitButton).toBeDisabled()

    // Fill with valid passwords
    const validPassword = generateTestPassword()
    await page.getByLabel('Huidig Wachtwoord', { exact: true }).fill(testPassword)
    await page.getByLabel('Nieuw Wachtwoord', { exact: true }).fill(validPassword)
    await page.getByLabel('Bevestig Nieuw Wachtwoord', { exact: true }).fill(validPassword)

    // Should now be enabled
    await expect(submitButton).toBeEnabled()
  })
})

test.describe('Passkey Manager', () => {
  let testEmail: string
  let testPassword: string

  test.beforeEach(async ({ page, request }) => {
    // Clean Mailpit inbox before each test
    const mailpit = createMailpitHelper(request)
    await mailpit.deleteAllMessages()

    // Create unique test user for each test
    testEmail = generateTestEmail('passkey')
    testPassword = generateTestPassword()

    const auth = new AuthHelper(page)

    // 1. Register the user
    await auth.register(testEmail, testPassword, 'Passkey Test User')
    await page.waitForLoadState('networkidle')

    // 2. Wait for verification email and get verification link
    const verificationEmail = await mailpit.waitForEmail(testEmail, {
      subject: /verify/i,
      timeout: 10000
    })
    const verificationLink = await mailpit.getVerificationLink(verificationEmail.ID)

    if (!verificationLink) {
      throw new Error('No verification link found in email')
    }

    // 3. Click verification link
    await page.goto(verificationLink)
    await page.waitForLoadState('networkidle')

    // 4. User should now be verified and logged in automatically
    // Wait for redirect to dashboard (autoSignInAfterVerification: true)
    await page.waitForURL('**/dashboard**', { timeout: 10000 })
  })

  test('shows add passkey modal', async ({ page }) => {
    await page.goto('/dashboard/account/security')
    await page.waitForLoadState('networkidle')

    await page.getByRole('button', { name: 'Passkey Toevoegen' }).click()

    // Modal should open (using Dutch translation)
    await expect(page.getByText('Registreer een Nieuwe Passkey')).toBeVisible()
    await expect(page.getByLabel('Passkey Naam')).toBeVisible()
  })

  test('shows empty state when no passkeys', async ({ page }) => {
    await page.goto('/dashboard/account/security')
    await page.waitForLoadState('networkidle')

    // Assuming fresh account (using Dutch translation)
    await expect(
      page.getByText('Nog geen passkeys geregistreerd')
    ).toBeVisible()
  })

  test('cancel button closes modal', async ({ page }) => {
    await page.goto('/dashboard/account/security')
    await page.waitForLoadState('networkidle')

    await page.getByRole('button', { name: 'Passkey Toevoegen' }).click()

    // Click cancel (using Dutch translation)
    await page.getByRole('button', { name: 'Annuleren' }).click()

    // Modal should close
    await expect(
      page.getByText('Registreer een Nieuwe Passkey')
    ).not.toBeVisible()
  })
})
