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

test.describe('Bug: Note move to notebook - REFRESH ISSUE', () => {
  test('should update UI immediately when moving note to notebook WITHOUT page refresh', async ({ page }) => {
    const timestamp = Date.now()

    // Step 1: Go to homepage (no login needed based on drag-drop tests)
    await page.goto('/')
    await page.waitForLoadState('networkidle')
    await page.waitForTimeout(2000)

    // Step 2: Create a test note
    const testNoteTitle = `TEST-${timestamp}-Move Note`
    const testNoteContent = `This is a test note to verify move bug. Timestamp: ${timestamp}`

    console.log('[TEST] Creating test note:', testNoteTitle)
    await page.click('input[placeholder="Take a note..."]')
    await page.fill('input[placeholder="Title"]', testNoteTitle)
    await page.fill('textarea[placeholder="Take a note..."]', testNoteContent)
    await page.click('button:has-text("Add")')
    await page.waitForTimeout(2000)

    // Step 3: Find the created note
    const notesBefore = await page.locator('[data-draggable="true"]').count()
    console.log('[TEST] Notes count after creation:', notesBefore)
    expect(notesBefore).toBeGreaterThan(0)

    // Step 4: Get the first note's ID and title
    const firstNote = page.locator('[data-draggable="true"]').first()
    const noteText = await firstNote.textContent()
    console.log('[TEST] First note text:', noteText?.substring(0, 100))

    // Step 5: Create a test notebook
    console.log('[TEST] Creating test notebook')
    const testNotebookName = `TEST-NOTEBOOK-${timestamp}`

    // Click the "Create Notebook" button (check for different possible selectors)
    const createNotebookBtn = page.locator('button:has-text("Créer"), button:has-text("Create"), button:has-text("+")').first()
    await createNotebookBtn.click()
    await page.waitForTimeout(500)

    // Fill notebook name
    const notebookInput = page.locator('input[name="name"], input[placeholder*="notebook"], input[placeholder*="nom"]').first()
    await notebookInput.fill(testNotebookName)

    // Submit
    const submitBtn = page.locator('button:has-text("Créer"), button:has-text("Create"), button[type="submit"]').first()
    await submitBtn.click()
    await page.waitForTimeout(2000)

    console.log('[TEST] Notebook created:', testNotebookName)

    // Step 6: Move the first note to the notebook
    console.log('[TEST] Moving note to notebook...')

    // Look for a way to move the note - try to find a menu or button on the note
    // Try to find a notebook menu or context menu
    const notebookMenuBtn = firstNote.locator('button[aria-label*="notebook"], button[title*="notebook"], button:has(.icon-folder)').first()

    if (await notebookMenuBtn.count() > 0) {
      console.log('[TEST] Found notebook menu button')
      await notebookMenuBtn.click()
      await page.waitForTimeout(500)

      // Select the created notebook
      const notebookOption = page.locator(`[role="menuitem"]:has-text("${testNotebookName}")`).first()
      if (await notebookOption.count() > 0) {
        await notebookOption.click()
        console.log('[TEST] Clicked notebook option')
      } else {
        console.log('[TEST] Notebook option not found in menu')
        // List all menu items for debugging
        const allMenuItems = await page.locator('[role="menuitem"]').allTextContents()
        console.log('[TEST] Available menu items:', allMenuItems)
      }
    } else {
      console.log('[TEST] Notebook menu button not found, trying drag and drop')

      // Alternative: Use drag and drop to move note to notebook
      const notebooksList = page.locator('[class*="notebook"], [class*="sidebar"]').locator(`text=${testNotebookName}`)
      const notebookCount = await notebooksList.count()
      console.log('[TEST] Found notebook in list:', notebookCount)

      if (notebookCount > 0) {
        const notebookElement = notebooksList.first()
        await firstNote.dragTo(notebookElement)
        console.log('[TEST] Dragged note to notebook')
      }
    }

    // Wait for the move operation to complete
    await page.waitForTimeout(3000)

    // CRITICAL CHECK: Is the note still visible WITHOUT refresh?
    const notesAfterMove = await page.locator('[data-draggable="true"]').count()
    console.log('[TEST] Notes count AFTER move (NO REFRESH):', notesAfterMove)

    // Get title of first note after move
    const firstNoteAfter = page.locator('[data-draggable="true"]').first()
    const firstNoteAfterTitle = await firstNoteAfter.locator('[class*="title"], h1, h2, h3').first().textContent()

    console.log('[TEST] First note title after move:', firstNoteAfterTitle)
    console.log('[TEST] Original note title:', testNoteTitle)

    // The bug is: the moved note is STILL VISIBLE in "Notes générales"
    // This means the UI did NOT update after the move
    if (firstNoteAfterTitle?.includes(testNoteTitle)) {
      console.log('[BUG CONFIRMED] Moved note is STILL VISIBLE - UI did not update!')
      console.log('[BUG CONFIRMED] This confirms the bug: triggerRefresh() is not working')

      // Take a screenshot for debugging
      await page.screenshot({ path: `playwright-report/bug-screenshot-${timestamp}.png` })
    } else {
      console.log('[SUCCESS] Moved note is no longer visible - UI updated correctly!')
    }

    // Now refresh the page to see what happens
    console.log('[TEST] Refreshing page...')
    await page.reload()
    await page.waitForLoadState('networkidle')
    await page.waitForTimeout(2000)

    const notesAfterRefresh = await page.locator('[data-draggable="true"]').count()
    console.log('[TEST] Notes count AFTER REFRESH:', notesAfterRefresh)

    // Check if the note is now gone after refresh
    const firstNoteAfterRefresh = await page.locator('[data-draggable="true"]').first()
    const firstNoteAfterRefreshTitle = await firstNoteAfterRefresh.locator('[class*="title"], h1, h2, h3').first().textContent()

    console.log('[TEST] First note title AFTER REFRESH:', firstNoteAfterRefreshTitle)

    if (firstNoteAfterRefreshTitle?.includes(testNoteTitle)) {
      console.log('[BUG CONFIRMED] Note is STILL visible after refresh too - move might have failed')
    } else {
      console.log('[SUCCESS] Note is gone after refresh - it was moved to notebook')
    }
  })
})
