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

test.describe('Memos', () => {
  test.beforeEach(async ({ page }) => {
    // Sign in before each test
    await page.goto('/auth');
    const emailInput = page.locator('input[type="email"]').or(page.locator('input[name="email"]')).first();
    const passwordInput = page.locator('input[type="password"]').first();
    const submitButton = page.getByRole('button', { name: /sign in/i }).or(page.locator('button[type="submit"]')).first();
    
    if (await emailInput.isVisible()) {
      await emailInput.fill('test@example.com');
      await passwordInput.fill('testpassword123');
      await submitButton.click();
      await page.waitForURL(/.*app.*/, { timeout: 10000 });
    }
  });

  test('should create a new memo', async ({ page }) => {
    await page.goto('/app');
    
    // Find memo editor (could be a button, textarea, or contenteditable)
    const editorTrigger = page.getByRole('button', { name: /new memo|write|create/i }).or(
      page.locator('textarea').or(page.locator('[contenteditable="true"]')).first()
    ).first();
    
    if (await editorTrigger.isVisible()) {
      await editorTrigger.click();
      
      // Wait for editor to be ready
      const editor = page.locator('textarea').or(page.locator('[contenteditable="true"]')).first();
      await expect(editor).toBeVisible({ timeout: 5000 });
      
      // Type memo content
      const memoContent = 'Test memo created by Playwright at ' + new Date().toISOString();
      await editor.fill(memoContent);
      
      // Save memo (look for save/submit button)
      const saveButton = page.getByRole('button', { name: /save|submit|post/i }).or(
        page.locator('button[type="submit"]')
      ).first();
      
      if (await saveButton.isVisible()) {
        await saveButton.click();
        
        // Wait for memo to appear in list
        await expect(page.getByText(memoContent)).toBeVisible({ timeout: 10000 });
      }
    }
  });

  test('should display memo list', async ({ page }) => {
    await page.goto('/app');
    
    // Wait for memos to load
    await page.waitForSelector('[data-testid="memo-card"]', { timeout: 10000 }).catch(() => {});
    
    // Check if memos are displayed
    const memos = page.locator('[data-testid="memo-card"]').or(page.locator('article'));
    const memoCount = await memos.count();
    
    // Should have at least some memos (or empty state)
    expect(memoCount).toBeGreaterThanOrEqual(0);
  });

  test('should navigate to memo detail page', async ({ page }) => {
    await page.goto('/app');
    await page.waitForSelector('[data-testid="memo-card"]', { timeout: 10000 }).catch(() => {});
    
    const firstMemo = page.locator('[data-testid="memo-card"]').or(page.locator('article').first()).first();
    if (await firstMemo.isVisible()) {
      // Get memo content to verify later
      const memoContent = await firstMemo.textContent();
      
      await firstMemo.click();
      
      // Should navigate to memo detail page
      await expect(page).toHaveURL(/.*memos\/.*/, { timeout: 5000 });
      
      // Verify memo content is displayed
      if (memoContent) {
        await expect(page.getByText(memoContent.substring(0, 50))).toBeVisible({ timeout: 5000 });
      }
    }
  });

  test('should edit memo', async ({ page }) => {
    await page.goto('/app');
    await page.waitForSelector('[data-testid="memo-card"]', { timeout: 10000 }).catch(() => {});
    
    const firstMemo = page.locator('[data-testid="memo-card"]').or(page.locator('article').first()).first();
    if (await firstMemo.isVisible()) {
      await firstMemo.click();
      await page.waitForURL(/.*memos\/.*/, { timeout: 5000 });
      
      // Find edit button
      const editButton = page.getByRole('button', { name: /edit/i }).or(
        page.locator('button').filter({ hasText: /edit/i })
      ).first();
      
      if (await editButton.isVisible()) {
        await editButton.click();
        
        // Wait for editor
        const editor = page.locator('textarea').or(page.locator('[contenteditable="true"]')).first();
        await expect(editor).toBeVisible({ timeout: 5000 });
        
        // Modify content
        const updatedContent = 'Updated memo content ' + new Date().toISOString();
        await editor.fill(updatedContent);
        
        // Save
        const saveButton = page.getByRole('button', { name: /save/i }).first();
        if (await saveButton.isVisible()) {
          await saveButton.click();
          
          // Verify update
          await expect(page.getByText(updatedContent)).toBeVisible({ timeout: 10000 });
        }
      }
    }
  });

  test('should filter memos by date', async ({ page }) => {
    await page.goto('/app');
    
    // Find date picker or calendar
    const datePicker = page.getByRole('button', { name: /date|calendar/i }).or(
      page.locator('input[type="date"]')
    ).first();
    
    if (await datePicker.isVisible()) {
      await datePicker.click();
      
      // Select today's date (adjust based on your date picker implementation)
      const today = new Date();
      const dateString = today.toISOString().split('T')[0];
      
      // Try to select date (implementation depends on your date picker)
      const dateOption = page.getByRole('button', { name: new RegExp(today.getDate().toString()) }).first();
      if (await dateOption.isVisible()) {
        await dateOption.click();
        
        // Verify URL has filter parameter
        await expect(page).toHaveURL(/.*filter.*displayTime.*/, { timeout: 5000 });
        
        // Verify memos are filtered
        await page.waitForTimeout(1000); // Wait for filter to apply
      }
    }
  });

  test('should filter memos by tag', async ({ page }) => {
    await page.goto('/app');
    await page.waitForSelector('[data-testid="memo-card"]', { timeout: 10000 }).catch(() => {});
    
    // Find a tag in a memo
    const tag = page.locator('[data-testid="tag"]').or(page.getByText(/^#\w+$/)).first();
    if (await tag.isVisible()) {
      const tagText = await tag.textContent();
      await tag.click();
      
      // Verify URL has tag filter
      await expect(page).toHaveURL(/.*tag.*/, { timeout: 5000 });
      
      // Verify filtered memos
      if (tagText) {
        await expect(page.getByText(tagText)).toBeVisible({ timeout: 5000 });
      }
    }
  });
});

