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

test.describe('Bug: Move note to notebook - DIRECT TEST', () => {
  test('BUG: Note should disappear from main page after moving to notebook', async ({ page }) => {
    const timestamp = Date.now()

    // Step 1: Go to homepage
    await page.goto('/')
    await page.waitForLoadState('networkidle')
    await page.waitForTimeout(2000)

    // Get initial note count
    const notesBefore = await page.locator('[data-draggable="true"]').count()
    console.log('[TEST] Initial notes count:', notesBefore)

    // Step 2: Create a test note
    const testNoteTitle = `TEST-BUG-${timestamp}`
    const testNoteContent = `Test content ${timestamp}`

    console.log('[TEST] Creating 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)

    const notesAfterCreation = await page.locator('[data-draggable="true"]').count()
    console.log('[TEST] Notes after creation:', notesAfterCreation)
    expect(notesAfterCreation).toBe(notesBefore + 1)

    // Step 3: Create a test notebook
    console.log('[TEST] Creating notebook')

    // Try to find and click "Create Notebook" button
    const createNotebookButtons = page.locator('button')
    const createButtonsCount = await createNotebookButtons.count()
    console.log('[TEST] Total buttons found:', createButtonsCount)

    // List all button texts for debugging
    for (let i = 0; i < Math.min(createButtonsCount, 10); i++) {
      const btn = createNotebookButtons.nth(i)
      const btnText = await btn.textContent()
      console.log(`[TEST] Button ${i}: "${btnText?.trim()}"`)
    }

    // Look for a "+" button or "Créer" button
    let createBtn = page.locator('button').filter({ hasText: '+' }).first()
    if (await createBtn.count() === 0) {
      createBtn = page.locator('button').filter({ hasText: 'Créer' }).first()
    }

    if (await createBtn.count() > 0) {
      await createBtn.click()
      await page.waitForTimeout(500)

      // Try to fill notebook name
      const testNotebookName = `TEST-NOTEBOOK-${timestamp}`

      // Look for any input field
      const inputs = page.locator('input')
      const inputCount = await inputs.count()
      console.log('[TEST] Input fields found:', inputCount)

      // Fill first input with notebook name
      if (inputCount > 0) {
        const firstInput = inputs.first()
        await firstInput.fill(testNotebookName)

        // Submit the form
        await page.keyboard.press('Enter')
        await page.waitForTimeout(2000)

        console.log('[TEST] Notebook created (or attempted)')
      }
    } else {
      console.log('[TEST] No create button found!')
    }

    // Take screenshot to see current state
    await page.screenshot({ path: `playwright-report/after-notebook-creation-${timestamp}.png` })
    console.log('[TEST] Screenshot saved')

    // Step 4: Try to move the note to the notebook using UI
    console.log('[TEST] Attempting to move note...')

    // Find the note we just created
    const ourNote = page.locator('[data-draggable="true"]').filter({ hasText: testNoteTitle })
    const ourNoteCount = await ourNote.count()
    console.log('[TEST] Our note found:', ourNoteCount)

    if (ourNoteCount > 0) {
      console.log('[TEST] Found our note, trying to move it')

      // Try to find any button/element in the note card
      const noteElement = await ourNote.innerHTML()
      console.log('[TEST] Note HTML:', noteElement.substring(0, 500))

      // Look for any clickable elements in the note
      const allButtonsInNote = await ourNote.locator('button').all()
      console.log('[TEST] Buttons in note:', allButtonsInNote.length)

      for (let i = 0; i < allButtonsInNote.length; i++) {
        const btn = allButtonsInNote[i]
        const btnText = await btn.textContent()
        const btnAriaLabel = await btn.getAttribute('aria-label')
        console.log(`[TEST] Note button ${i}: text="${btnText}" aria-label="${btnAriaLabel}"`)
      }

      // Take screenshot before move attempt
      await page.screenshot({ path: `playwright-report/before-move-${timestamp}.png` })

      // Try to click any button that might be related to notebooks
      if (allButtonsInNote.length > 0) {
        // Try clicking the first few buttons
        for (let i = 0; i < Math.min(allButtonsInNote.length, 3); i++) {
          const btn = allButtonsInNote[i]
          const btnText = await btn.textContent()

          console.log(`[TEST] Clicking button ${i}: "${btnText}"`)
          await btn.click()
          await page.waitForTimeout(1000)

          // Take screenshot after each click
          await page.screenshot({ path: `playwright-report/after-click-${i}-${timestamp}.png` })

          // Check if a menu opened
          const menuItems = page.locator('[role="menuitem"], [role="option"]')
          const menuItemCount = await menuItems.count()
          console.log(`[TEST] Menu items after click ${i}:`, menuItemCount)

          if (menuItemCount > 0) {
            // List menu items
            for (let j = 0; j < Math.min(menuItemCount, 5); j++) {
              const item = menuItems.nth(j)
              const itemText = await item.textContent()
              console.log(`[TEST] Menu item ${j}: "${itemText}"`)
            }

            // Try to click the first menu item (likely our notebook)
            const firstMenuItem = menuItems.first()
            await firstMenuItem.click()
            await page.waitForTimeout(2000)
            break
          }

          // Close menu if any (press Escape)
          await page.keyboard.press('Escape')
          await page.waitForTimeout(500)
        }
      }
    }

    // CRITICAL: Check if note is still visible WITHOUT refresh
    await page.waitForTimeout(2000)

    const ourNoteAfterMove = await page.locator('[data-draggable="true"]').filter({ hasText: testNoteTitle }).count()
    const allNotesAfterMove = await page.locator('[data-draggable="true"]').count()

    console.log('[TEST] ===== RESULTS =====')
    console.log('[TEST] Our note still visible in main page:', ourNoteAfterMove)
    console.log('[TEST] Total notes in main page:', allNotesAfterMove)

    // Take final screenshot
    await page.screenshot({ path: `playwright-report/final-state-${timestamp}.png` })
    console.log('[TEST] Final screenshot saved')

    // THE BUG: If ourNoteAfterMove === 1, the note is still visible - triggerRefresh() didn't work!
    if (ourNoteAfterMove === 1) {
      console.log('[BUG CONFIRMED] triggerRefresh() is NOT working - note still visible!')
      console.log('[BUG CONFIRMED] This is the exact bug the user reported')
    } else {
      console.log('[SUCCESS] Note disappeared from main page - triggerRefresh() worked!')
    }
  })
})
