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

const CHILD_NAME = 'AssignRewardChild'
const REW1_NAME = 'AssignTestReward1'
const REW2_NAME = 'AssignTestReward2'
const REW3_NAME = 'AssignTestReward3'

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 createTestReward(request: APIRequestContext, name: string): Promise<string> {
  await request.put('/api/reward/add', { data: { name, description: 'Test reward', cost: 10 } })
  const res = await request.get('/api/reward/list')
  const data = (await res.json()) as { rewards?: { name: string; id: string }[] }
  return data.rewards?.find((r) => r.name === name)?.id ?? ''
}

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

  let childId = ''
  let rew1Id = ''
  let rew2Id = ''
  let rew3Id = ''

  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 rewards from a previous run
    const rewardRes = await request.get('/api/reward/list')
    const rewardData = await rewardRes.json()
    for (const r of rewardData.rewards ?? []) {
      if ([REW1_NAME, REW2_NAME, REW3_NAME].includes(r.name)) {
        await request.delete(`/api/reward/${r.id}`)
      }
    }

    childId = await createTestChild(request, CHILD_NAME)
    rew1Id = await createTestReward(request, REW1_NAME)
    rew2Id = await createTestReward(request, REW2_NAME)
    rew3Id = await createTestReward(request, REW3_NAME)
  })

  test.afterAll(async ({ request }) => {
    if (childId) await request.delete(`/api/child/${childId}`)
    if (rew1Id) await request.delete(`/api/reward/${rew1Id}`)
    if (rew2Id) await request.delete(`/api/reward/${rew2Id}`)
    if (rew3Id) await request.delete(`/api/reward/${rew3Id}`)
  })

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

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

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

    // Test-specific rewards are listed
    await expect(page.getByText(REW1_NAME, { exact: true })).toBeVisible()
    await expect(page.getByText(REW2_NAME, { exact: true })).toBeVisible()

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

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

    // Select two rewards
    await page.getByText(REW1_NAME, { exact: true }).click()
    await page.getByText(REW2_NAME, { exact: true }).click()

    await expect(
      page.locator('.list-row').filter({ hasText: REW1_NAME }).locator('.list-checkbox'),
    ).toBeChecked()
    await expect(
      page.locator('.list-row').filter({ hasText: REW2_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 Rewards' })).toBeVisible()
    await expect(page.getByText(REW1_NAME)).toBeVisible()
    await expect(page.getByText(REW2_NAME)).toBeVisible()
  })

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

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

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

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

    // Uncheck the previously assigned rewards
    await page.getByText(REW1_NAME, { exact: true }).click()
    await page.getByText(REW2_NAME, { exact: true }).click()

    await expect(
      page.locator('.list-row').filter({ hasText: REW1_NAME }).locator('.list-checkbox'),
    ).not.toBeChecked()
    await expect(
      page.locator('.list-row').filter({ hasText: REW2_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 Rewards' })).toBeVisible()
    await expect(page.getByText(REW1_NAME)).not.toBeVisible()
    await expect(page.getByText(REW2_NAME)).not.toBeVisible()
  })

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

    // Check an item
    await page.getByText(REW3_NAME, { exact: true }).click()
    await expect(
      page.locator('.list-row').filter({ hasText: REW3_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-rewards`)
    await expect(page.getByRole('heading', { name: 'Assign Rewards' })).toBeVisible()
    await expect(
      page.locator('.list-row').filter({ hasText: REW3_NAME }).locator('.list-checkbox'),
    ).not.toBeChecked()
  })
})
