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

test.describe('Filters', () => {
  const baseURL = process.env.BASE_URL || 'http://127.0.0.1:3001';

  test.beforeEach(async ({ page }) => {
    // Sign in before each test
    await page.goto(`${baseURL}/auth`);
    const usernameInput = page.getByPlaceholder(/Enter your username/i).or(page.locator('input').first());
    const passwordInput = page.getByPlaceholder(/Enter your password/i).or(page.locator('input[type="password"]'));
    const submitButton = page.getByRole('button', { name: /sign in|login|đăng nhập/i }).or(page.locator('button[type="submit"]')).first();
    
    try {
      await usernameInput.waitFor({ state: 'visible', timeout: 5000 });
      await usernameInput.fill('e2etest');
      await passwordInput.fill('Test12345!');
      await submitButton.click();
      await page.waitForURL(/.*app(\/.*)?/, { timeout: 15000 }).catch(() => {});
    } catch (e) {
      console.log('Already logged in or auth form not visible');
    }
    await page.goto(`${baseURL}/`);
  });

  test('should filter by date using calendar', async ({ page }) => {
    // Wait for feed to load
    await page.waitForSelector('[data-testid="memo-card"], article, .memo-card', { timeout: 10000 }).catch(() => {});
    
    // Find date picker
    const datePicker = page.getByRole('button', { name: /date|calendar/i }).or(
      page.locator('input[type="date"]')
    ).first();
    
    try {
      await datePicker.waitFor({ state: 'visible', timeout: 5000 });
      await datePicker.click();
      
      // Select a date (e.g., today)
      const today = new Date();
      const dateButton = page.getByRole('button', { name: new RegExp(today.getDate().toString()) }).first();
      
      await dateButton.waitFor({ state: 'visible', timeout: 5000 });
      await dateButton.click();
      
      // Verify filter is applied in URL
      await expect(page).toHaveURL(/.*filter.*displayTime.*/, { timeout: 5000 });
      
      // Verify memos are filtered (wait for list to update)
      await page.waitForTimeout(1000);
    } catch (e) {
      console.log("Filter by date failed");
    }
  });

  test('should filter by tag', async ({ page }) => {
    await page.waitForSelector('[data-testid="memo-card"], article, .memo-card', { timeout: 10000 }).catch(() => {});
    
    // Find a tag
    const tag = page.locator('[data-testid="tag"], .tag').or(page.getByText(/^#\w+$/)).first();
    try {
      await tag.waitFor({ state: 'visible', timeout: 5000 });
      const tagText = await tag.textContent();
      await tag.click();
      
      // Verify URL contains tag filter
      await expect(page).toHaveURL(/.*tag.*/, { timeout: 5000 });
      
      // Verify filtered results
      if (tagText) {
        // All visible memos should have this tag
        const memos = page.locator('[data-testid="memo-card"], article, .memo-card');
        const count = await memos.count();
        
        if (count > 0) {
          // Check first few memos have the tag
          for (let i = 0; i < Math.min(3, count); i++) {
            const memo = memos.nth(i);
            await expect(memo.getByText(tagText)).toBeVisible({ timeout: 2000 }).catch(() => {});
          }
        }
      }
    } catch (e) {
      console.log("Filter by tag failed");
    }
  });

  test('should clear filter', async ({ page }) => {
    await page.waitForSelector('[data-testid="memo-card"], article, .memo-card', { timeout: 10000 }).catch(() => {});
    
    // Apply a filter first
    const tag = page.locator('[data-testid="tag"], .tag').or(page.getByText(/^#\w+$/)).first();
    try {
      await tag.waitFor({ state: 'visible', timeout: 5000 });
      await tag.click();
      await page.waitForURL(/.*tag.*/, { timeout: 5000 });
      
      // Find clear filter button
      const clearButton = page.getByRole('button', { name: /clear|reset|remove|xóa/i }).or(
        page.locator('button').filter({ hasText: /clear|×|x\b/i })
      ).first();
      
      await clearButton.waitFor({ state: 'visible', timeout: 5000 });
      await clearButton.click();
      
      // Verify filter is removed from URL
      await expect(page).not.toHaveURL(/.*tag.*/, { timeout: 5000 });
    } catch (e) {
      console.log("Clear filter failed");
    }
  });

  test('should persist filter on page refresh', async ({ page }) => {
    await page.waitForSelector('[data-testid="memo-card"], article, .memo-card', { timeout: 10000 }).catch(() => {});
    
    // Apply filter
    const tag = page.locator('[data-testid="tag"], .tag').or(page.getByText(/^#\w+$/)).first();
    try {
      await tag.waitFor({ state: 'visible', timeout: 5000 });
      const tagText = await tag.textContent();
      await tag.click();
      await page.waitForURL(/.*tag.*/, { timeout: 5000 });
      
      // Refresh page
      await page.reload();
      await page.waitForSelector('[data-testid="memo-card"], article, .memo-card', { timeout: 10000 }).catch(() => {});
      
      // Verify filter is still applied
      await expect(page).toHaveURL(/.*tag.*/, { timeout: 5000 });
      
      // Verify filtered results are still shown
      if (tagText) {
        await expect(page.getByText(tagText).first()).toBeVisible({ timeout: 5000 }).catch(() => {});
      }
    } catch (e) {
      console.log("Persist filter failed");
    }
  });
});

