import { test, expect, type APIRequestContext } from '@playwright/test'

const CHILD_NAME = 'AssignPenaltyChild'
const PEN1_NAME = 'AssignTestPenalty1'
const PEN2_NAME = 'AssignTestPenalty2'
const PEN3_NAME = 'AssignTestPenalty3'

async function createTestChild(request: APIRequestContext, name: string): Promise<string> {
  await request.put('/api/child/add', { data: { name, age: 8 } })
  const res = await request.get('/api/child/list')
  const data = (await res.json()) as { children?: { name: string; id: string }[] }
  return data.children?.find((c) => c.name === name)?.id ?? ''
}

async function createTestTask(
  request: APIRequestContext,
  name: string,
  type: 'chore' | 'kindness' | 'penalty',
): Promise<string> {
  await request.put('/api/task/add', { data: { name, points: 5, type } })
  const res = await request.get('/api/task/list')
  const data = (await res.json()) as { tasks?: { name: string; id: string }[] }
  return data.tasks?.find((t) => t.name === name)?.id ?? ''
}

test.describe('Penalty assignment', () => {
  test.describe.configure({ mode: 'serial' })

  let childId = ''
  let pen1Id = ''
  let pen2Id = ''
  let pen3Id = ''

  test.beforeAll(async ({ request }) => {
    // Clean up any stale child from a previous run
    const listRes = await request.get('/api/child/list')
    const listData = await listRes.json()
    for (const c of listData.children ?? []) {
      if (c.name === CHILD_NAME) await request.delete(`/api/child/${c.id}`)
    }

    // Clean up any stale test tasks from a previous run
    const taskRes = await request.get('/api/task/list')
    const taskData = await taskRes.json()
    for (const t of taskData.tasks ?? []) {
      if ([PEN1_NAME, PEN2_NAME, PEN3_NAME].includes(t.name)) {
        await request.delete(`/api/task/${t.id}`)
      }
    }

    childId = await createTestChild(request, CHILD_NAME)
    pen1Id = await createTestTask(request, PEN1_NAME, 'penalty')
    pen2Id = await createTestTask(request, PEN2_NAME, 'penalty')
    pen3Id = await createTestTask(request, PEN3_NAME, 'penalty')
  })

  test.afterAll(async ({ request }) => {
    if (childId) await request.delete(`/api/child/${childId}`)
    if (pen1Id) await request.delete(`/api/task/${pen1Id}`)
    if (pen2Id) await request.delete(`/api/task/${pen2Id}`)
    if (pen3Id) await request.delete(`/api/task/${pen3Id}`)
  })

  test('"Assign Penalties" button navigates to the penalty assign view', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    await expect(page.getByRole('button', { name: 'Assign Penalties' })).toBeVisible()

    await page.getByRole('button', { name: 'Assign Penalties' }).click()
    await page.waitForURL(new RegExp(`/parent/${childId}/assign-penalties(\\?|$)`))

    await expect(page.getByRole('heading', { name: 'Assign Penalties' })).toBeVisible()

    // Test-specific penalty items are listed
    await expect(page.getByText(PEN1_NAME, { exact: true })).toBeVisible()
    await expect(page.getByText(PEN2_NAME, { exact: true })).toBeVisible()

    // Fresh child — nothing pre-checked
    await expect(
      page.locator('.list-row').filter({ hasText: PEN1_NAME }).locator('.list-checkbox'),
    ).not.toBeChecked()
  })

  test('Select penalties and submit — items appear in ParentView penalties section', async ({
    page,
  }) => {
    await page.goto(`/parent/${childId}`)
    await page.getByRole('button', { name: 'Assign Penalties' }).click()
    await page.waitForURL(new RegExp(`/parent/${childId}/assign-penalties(\\?|$)`))
    await expect(page.getByRole('heading', { name: 'Assign Penalties' })).toBeVisible()

    // Select two penalties
    await page.getByText(PEN1_NAME, { exact: true }).click()
    await page.getByText(PEN2_NAME, { exact: true }).click()

    await expect(
      page.locator('.list-row').filter({ hasText: PEN1_NAME }).locator('.list-checkbox'),
    ).toBeChecked()
    await expect(
      page.locator('.list-row').filter({ hasText: PEN2_NAME }).locator('.list-checkbox'),
    ).toBeChecked()

    await page.getByRole('button', { name: 'Submit' }).click()
    await page.waitForURL(new RegExp(`/parent/${childId}$`))

    await expect(page.getByRole('button', { name: 'Assign Penalties' })).toBeVisible()
    await expect(page.getByText(PEN1_NAME)).toBeVisible()
    await expect(page.getByText(PEN2_NAME)).toBeVisible()
  })

  test('Re-opening assign view shows assigned penalties as pre-checked', async ({ page }) => {
    await page.goto(`/parent/${childId}/assign-penalties`)
    await expect(page.getByRole('heading', { name: 'Assign Penalties' })).toBeVisible()

    // Previously assigned items should be pre-checked
    await expect(
      page.locator('.list-row').filter({ hasText: PEN1_NAME }).locator('.list-checkbox'),
    ).toBeChecked()
    await expect(
      page.locator('.list-row').filter({ hasText: PEN2_NAME }).locator('.list-checkbox'),
    ).toBeChecked()

    // An unassigned item should not be checked
    await expect(
      page.locator('.list-row').filter({ hasText: PEN3_NAME }).locator('.list-checkbox'),
    ).not.toBeChecked()
  })

  test('Uncheck all penalties and submit — items are removed from ParentView', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    await page.getByRole('button', { name: 'Assign Penalties' }).click()
    await page.waitForURL(new RegExp(`/parent/${childId}/assign-penalties(\\?|$)`))
    await expect(page.getByRole('heading', { name: 'Assign Penalties' })).toBeVisible()

    // Uncheck the previously assigned penalties
    await page.getByText(PEN1_NAME, { exact: true }).click()
    await page.getByText(PEN2_NAME, { exact: true }).click()

    await expect(
      page.locator('.list-row').filter({ hasText: PEN1_NAME }).locator('.list-checkbox'),
    ).not.toBeChecked()
    await expect(
      page.locator('.list-row').filter({ hasText: PEN2_NAME }).locator('.list-checkbox'),
    ).not.toBeChecked()

    await page.getByRole('button', { name: 'Submit' }).click()
    await page.waitForURL(new RegExp(`/parent/${childId}$`))

    await expect(page.getByRole('button', { name: 'Assign Penalties' })).toBeVisible()
    await expect(page.getByText(PEN1_NAME)).not.toBeVisible()
    await expect(page.getByText(PEN2_NAME)).not.toBeVisible()
  })

  test('Cancel does not persist selection changes', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    await page.getByRole('button', { name: 'Assign Penalties' }).click()
    await page.waitForURL(new RegExp(`/parent/${childId}/assign-penalties(\\?|$)`))
    await expect(page.getByRole('heading', { name: 'Assign Penalties' })).toBeVisible()

    // Check an item
    await page.getByText(PEN3_NAME, { exact: true }).click()
    await expect(
      page.locator('.list-row').filter({ hasText: PEN3_NAME }).locator('.list-checkbox'),
    ).toBeChecked()

    // Cancel instead of submitting
    await page.getByRole('button', { name: 'Cancel' }).click()
    await page.waitForURL(new RegExp(`/parent/${childId}$`))

    // Navigate back and verify the selection was not saved
    await page.goto(`/parent/${childId}/assign-penalties`)
    await expect(page.getByRole('heading', { name: 'Assign Penalties' })).toBeVisible()
    await expect(
      page.locator('.list-row').filter({ hasText: PEN3_NAME }).locator('.list-checkbox'),
    ).not.toBeChecked()
  })
})
