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

export class AdminLoginPage {
  readonly page: Page;
  readonly usernameInput: Locator;
  readonly passwordInput: Locator;
  readonly submitButton: Locator;
  readonly togglePasswordButton: Locator;
  readonly pageTitle: Locator;
  readonly welcomeText: Locator;
  readonly successToast: Locator;
  readonly errorToast: Locator;
  readonly usernameError: Locator;
  readonly passwordError: Locator;
  readonly testAccountInfo: Locator;
  readonly loadingSpinner: Locator;
  readonly backgroundElement: Locator;
  readonly loginCard: Locator;

  constructor(page: Page) {
    this.page = page;
    this.usernameInput = page.getByPlaceholder('请输入用户名');
    this.passwordInput = page.getByPlaceholder('请输入密码');
    this.submitButton = page.getByRole('button', { name: '登录' });
    this.togglePasswordButton = page.locator('button:has(svg)').last();
    this.pageTitle = page.getByRole('heading', { name: '管理后台登录' });
    this.welcomeText = page.getByText('请输入您的账号和密码继续操作');
    this.successToast = page.locator('[data-sonner-toast][data-type="success"]');
    this.errorToast = page.locator('[data-sonner-toast][data-type="error"]');
    this.usernameError = page.locator('text=请输入用户名');
    this.passwordError = page.locator('text=请输入密码');
    this.testAccountInfo = page.locator('text=测试账号:');
    this.loadingSpinner = page.locator('[aria-busy="true"], .loading-spinner, .spinner');
    this.backgroundElement = page.locator('div.flex.items-center.justify-center').first();
    this.loginCard = page.locator('.shadow-xl').first();
  }

  async goto() {
    await this.page.goto('/admin/login');
    await this.page.waitForLoadState('networkidle');
  }


  async expectLoginSuccess() {
    // 登录成功后应该重定向到管理后台dashboard
    await expect(this.page).toHaveURL('/admin/dashboard');
    await expect(this.page.locator('text=登录成功')).toBeVisible();
  }

  async expectLoginError() {
    await expect(this.errorToast).toBeVisible();
  }

  async expectToBeVisible(options?: { timeout?: number }) {
    await expect(this.pageTitle).toBeVisible(options);
    await expect(this.usernameInput).toBeVisible(options);
    await expect(this.passwordInput).toBeVisible(options);
    await expect(this.submitButton).toBeVisible(options);
  }

  async login(username: string, password: string) {
    await this.usernameInput.fill(username);
    await this.passwordInput.fill(password);
    await this.submitButton.click();

    // 等待登录完成
    await this.page.waitForLoadState('networkidle');
    await this.page.waitForTimeout(2000);
  }

  clone(newPage: Page): AdminLoginPage {
    return new AdminLoginPage(newPage);
  }
}