import type { Page } from "playwright";
import type { FlockTestAccount } from "@/lib/flock/env";
import { getFlockFieldPauseMs } from "@/lib/flock/env";
import {
  flockQuoteLimitMessage,
  flockRegistrationErrorMessage,
  isFlockQuoteLimitReached,
} from "@/workers/rpa/flock/page-state";
import { waitWithFlockStallWatch } from "@/workers/rpa/flock/stall-watch";

export async function isFlockRegistrationPage(page: Page): Promise<boolean> {
  const url = page.url();
  if (/signup|register|create.*account/i.test(url)) {
    return true;
  }

  if ((await page.getByTestId(/fulfillment-option/).count()) > 0) {
    return false;
  }
  if ((await page.getByText(/Explore your custom quote options/i).count()) > 0) {
    return false;
  }

  const hasHeading =
    (await page.getByText(/Create your free account/i).count()) > 0;
  const hasFirstName =
    (await page.getByRole("textbox", { name: /First name/i }).count()) > 0;
  const hasWorkEmail =
    (await page.getByRole("textbox", { name: /Work email/i }).count()) > 0;

  return hasHeading && hasFirstName && hasWorkEmail;
}

export async function isFlockQuoteResultsPage(page: Page): Promise<boolean> {
  if ((await page.getByTestId(/fulfillment-option/).count()) > 0) {
    return true;
  }
  const body = await page.locator("body").innerText().catch(() => "");
  return (
    (/Explore your custom quote options/i.test(body) &&
      !/Create your free account/i.test(body)) ||
    /still looking for the best rates|Hold tight/i.test(body)
  );
}

async function fillRoleTextbox(
  page: Page,
  name: RegExp,
  value: string,
  fieldLabel: string,
): Promise<boolean> {
  const loc = page.getByRole("textbox", { name }).first();
  try {
    await loc.waitFor({ state: "visible", timeout: 15_000 });
  } catch {
    return false;
  }

  const enabled = await waitWithFlockStallWatch(
    page,
    `注册-${fieldLabel}可编辑`,
    async () => loc.isEnabled().catch(() => false),
    { timeoutMs: 8_000, pollMs: 200 },
  );
  if (!enabled.ok || !(await loc.isEnabled().catch(() => false))) {
    return false;
  }

  await loc.click();
  await loc.fill("");
  await loc.pressSequentially(value, { delay: 12 });
  await loc.evaluate((el) => {
    el.dispatchEvent(new Event("input", { bubbles: true }));
    el.dispatchEvent(new Event("change", { bubbles: true }));
    el.dispatchEvent(new Event("blur", { bubbles: true }));
  });
  // 字段间停顿（embed 默认 300ms；batch 可设 1000）
  const pauseMs = getFlockFieldPauseMs();
  if (pauseMs > 0) {
    await page.waitForTimeout(pauseMs);
  }
  return true;
}

async function selectShipmentsPerMonth(
  page: Page,
  label: string,
): Promise<void> {
  const combobox = page
    .getByRole("combobox", { name: /Average company-wide dry van/i })
    .first();
  if ((await combobox.count()) === 0) {
    return;
  }
  await combobox.click();
  await page.waitForTimeout(400);

  const listbox = page.getByRole("listbox").last();
  await listbox.waitFor({ state: "visible", timeout: 8_000 }).catch(() => undefined);

  const optionPatterns = [
    label.replace(/^1-/, "-"),
    label,
    "1-25",
    "-25",
  ];
  for (const pattern of optionPatterns) {
    const opt = page.getByRole("option", { name: pattern }).first();
    if ((await opt.count()) > 0) {
      await opt.click();
      return;
    }
  }

  await page.keyboard.press("ArrowDown").catch(() => undefined);
  await page.keyboard.press("Enter").catch(() => undefined);
}

/**
 * 官网在部分线路会先弹出「Create your free account」再展示报价。
 * 使用测试账号池自动填写（PRD §14.5）。
 */
export async function completeFlockRegistrationIfNeeded(
  page: Page,
  account: FlockTestAccount,
): Promise<boolean> {
  const limitMsg = await flockQuoteLimitMessage(page);
  if (limitMsg) {
    return false;
  }

  if (!(await isFlockRegistrationPage(page))) {
    return false;
  }

  await page.waitForLoadState("domcontentloaded").catch(() => undefined);
  await page.waitForTimeout(400);

  if (await isFlockQuoteLimitReached(page)) {
    return false;
  }

  if (!(await fillRoleTextbox(page, /First name/i, account.firstName, "名"))) {
    return false;
  }
  if (!(await fillRoleTextbox(page, /Last name/i, account.lastName, "姓"))) {
    return false;
  }
  if (!(await fillRoleTextbox(page, /Company name/i, account.company, "公司"))) {
    return false;
  }
  if (!(await fillRoleTextbox(page, /Phone number/i, account.phone, "电话"))) {
    return false;
  }
  if (!(await fillRoleTextbox(page, /Work email/i, account.email, "邮箱"))) {
    return false;
  }
  await selectShipmentsPerMonth(page, account.shipmentsPerMonth);

  const submit = page
    .getByRole("button", {
      name: /Get instant quote|获取即时报价/i,
    })
    .first();
  if ((await submit.count()) === 0) {
    return false;
  }

  const submitReady = await waitWithFlockStallWatch(
    page,
    "注册-Get instant quote可点击",
    async () => submit.isEnabled().catch(() => false),
    { timeoutMs: 8_000, pollMs: 300 },
  );
  if (!submitReady.ok || !(await submit.isEnabled().catch(() => false))) {
    return false;
  }

  await submit.click();

  const leftRegistration = await waitWithFlockStallWatch(
    page,
    "注册-等待离开注册页",
    async () => !(await isFlockRegistrationPage(page)),
    { timeoutMs: 8_000, pollMs: 400 },
  );
  if (!leftRegistration.ok) {
    const regErr = await flockRegistrationErrorMessage(page);
    if (regErr) {
      console.warn(`[flock-rpa] ${regErr}`);
    }
  }
  return leftRegistration.ok;
}
