// spec: e2e/plans/task-modified.plan copy.md

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

const CHILD_NAME = 'ModifyPenaltyChild'
const PEN_NAME = 'ModifyTestPenalty'
const PEN_HELPER_NAME = 'ModifyPenaltyHelper'
const PEN_POINTS = 5

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

async function createTask(
  request: APIRequestContext,
  name: string,
  type: 'chore' | 'kindness' | 'penalty',
  points: number,
): Promise<string> {
  const pre = await request.get('/api/task/list')
  for (const t of (await pre.json()).tasks ?? []) {
    if (t.name === name) await request.delete(`/api/task/${t.id}`)
  }
  await request.put('/api/task/add', { data: { name, points, type } })
  const list = await request.get('/api/task/list')
  const { tasks } = (await list.json()) as { tasks: { name: string; id: string }[] }
  return tasks?.find((t) => t.name === name)?.id ?? ''
}

function penaltySection(page: Page): Locator {
  return page.locator('.child-list-container').filter({
    has: page.locator('h3', { hasText: 'Penalties' }),
  })
}

async function openEditModal(page: Page, card: Locator): Promise<void> {
  await card.click()
  await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
  await card.getByTitle('Edit custom value').click()
  await expect(page.getByRole('button', { name: 'Save' })).toBeVisible()
}

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

  let childId = ''
  let penId = ''
  let penHelperId = ''

  test.beforeAll(async ({ request }) => {
    childId = await createChild(request, CHILD_NAME)
    penId = await createTask(request, PEN_NAME, 'penalty', PEN_POINTS)
    penHelperId = await createTask(request, PEN_HELPER_NAME, 'penalty', PEN_POINTS)
    await request.put(`/api/child/${childId}/set-tasks`, {
      data: { task_ids: [penId, penHelperId], type: 'penalty' },
    })
  })

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

  test('Edit button appears on first click of a penalty card', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })

    await expect(card.getByTitle('Edit custom value')).not.toBeVisible()
    await card.click()
    await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
    await expect(card.getByTitle('Edit custom value')).toBeVisible()
  })

  test('Edit button disappears when clicking a different penalty card', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const section = penaltySection(page)
    const card = section.locator('.item-card').filter({ hasText: PEN_NAME })
    const helperCard = section.locator('.item-card').filter({ hasText: PEN_HELPER_NAME })
    await card.waitFor({ state: 'visible' })
    await helperCard.waitFor({ state: 'visible' })

    await card.click()
    await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
    await expect(card.getByTitle('Edit custom value')).toBeVisible()

    await helperCard.click()
    await expect(card.getByTitle('Edit custom value')).not.toBeVisible()
  })

  test('Edit button opens modal with penalty name and "Assign new points" subtitle', async ({
    page,
  }) => {
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })

    await card.click()
    await expect(card).toHaveClass(/item-ready/, { timeout: 3000 })
    await card.getByTitle('Edit custom value').click()

    await expect(page.locator('.modal-title')).toHaveText(PEN_NAME)
    await expect(page.locator('.modal-subtitle')).toContainText('new points')
    await page.getByRole('button', { name: 'Cancel' }).click()
  })

  test('Input is pre-populated with the raw point value (positive, not negated)', async ({
    page,
  }) => {
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })

    await openEditModal(page, card)
    // The input holds the positive magnitude; the negative display is a UI convention
    await expect(page.locator('#custom-value')).toHaveValue(String(PEN_POINTS))
    await page.getByRole('button', { name: 'Cancel' }).click()
  })

  test('Cancel does not change the display', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })

    await openEditModal(page, card)
    await page.locator('#custom-value').fill('99')
    await page.getByRole('button', { name: 'Cancel' }).click()

    await expect(page.getByRole('button', { name: 'Save' })).not.toBeVisible()
    // Penalty displays points negated: -5 Points
    await expect(card.locator('.item-points')).toContainText(`-${PEN_POINTS} Points`)
    await expect(card.locator('.override-badge')).not.toBeVisible()
  })

  test('Saving a new value updates card to show negated override and ⭐ badge', async ({
    page,
  }) => {
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })

    await openEditModal(page, card)
    await page.locator('#custom-value').fill('12')
    await page.getByRole('button', { name: 'Save' }).click()

    await expect(page.getByRole('button', { name: 'Save' })).not.toBeVisible()
    await expect(card.locator('.item-points')).toContainText('-12 Points')
    await expect(card.locator('.override-badge')).toBeVisible()
  })

  test('Negative value disables the Save button', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })

    await openEditModal(page, card)
    await page.locator('#custom-value').fill('-1')
    await expect(page.getByRole('button', { name: 'Save' })).toBeDisabled()
    await page.getByRole('button', { name: 'Cancel' }).click()
  })

  test('Value above 10000 disables Save; exactly 10000 enables it', async ({ page }) => {
    await page.goto(`/parent/${childId}`)
    const card = penaltySection(page).locator('.item-card').filter({ hasText: PEN_NAME })
    await card.waitFor({ state: 'visible' })

    await openEditModal(page, card)
    await page.locator('#custom-value').fill('10001')
    await expect(page.getByRole('button', { name: 'Save' })).toBeDisabled()
    await page.locator('#custom-value').fill('10000')
    await expect(page.getByRole('button', { name: 'Save' })).toBeEnabled()
    await page.getByRole('button', { name: 'Cancel' }).click()
  })
})
