import { expect, type Page } from "@playwright/test";
import path from "node:path";

export const DEV_OTP = "1234";

/** Unique phone per run so dev-mock starts a fresh onboarding session. */
export function uniqueTestPhone(): string {
  const suffix = Date.now().toString().slice(-7);
  return `+99890${suffix}`;
}

async function clickSaveContinue(page: Page) {
  const btn = page.getByRole("button", { name: /Saqlash va davom etish|Сохранить и продолжить/ });
  await expect(btn).toBeEnabled({ timeout: 15_000 });
  await btn.click();
}

export async function authenticateViaApply(page: Page, phone: string) {
  await page.goto("/farmers/apply");
  await expect(page.locator("h1")).toContainText("onboarding");

  await page.fill("#apply-phone", phone);
  await page.click("button:has-text('Send Verification Code')");
  await expect(page.locator("#apply-otp")).toBeVisible();
  await page.fill("#apply-otp", DEV_OTP);
  await page.click("button:has-text('Continue to Application')");

  await page.waitForURL("**/farmers/onboarding");
  await expect(page.locator("text=Loading your application...")).toBeHidden({
    timeout: 20_000,
  });
}

export async function completeAccountStep(page: Page, phone: string) {
  await expect(page.locator("h2")).toContainText("Create your account");
  await expect(page.locator("text=Loading account...")).toBeHidden({ timeout: 20_000 });

  const continueBtn = page.getByRole("button", { name: "Continue", exact: true });
  if (await continueBtn.isVisible()) {
    await continueBtn.click();
    await expect(page.locator("h2")).toContainText(/Rozilik|Согласие/, { timeout: 20_000 });
    return;
  }

  await page.fill("#phone", phone);
  await page.click("button:has-text('Send OTP')");
  await page.fill("#otp", DEV_OTP);
  await page.click("button:has-text('Verify & Continue')");
  await expect(page.locator("h2")).toContainText(/Rozilik|Согласие/, { timeout: 20_000 });
}

export async function completeConsentStep(page: Page) {
  await expect(page.locator("h2")).toContainText(/Rozilik|Согласие/);

  const consentLabels = page.locator("label:has(input[type='checkbox'])");
  await expect(consentLabels.first()).toBeVisible({ timeout: 15_000 });
  const count = await consentLabels.count();
  expect(count).toBeGreaterThan(0);
  for (let i = 0; i < count; i++) {
    await consentLabels.nth(i).click();
  }

  const continueBtn = page.getByRole("button", { name: /Qabul qilish|Принять и продолжить/ });
  await expect(continueBtn).toBeEnabled({ timeout: 5_000 });
  await continueBtn.click();
  await expect(page.locator("h2")).toContainText("Identity", { timeout: 20_000 });
}

export async function verifyKycOnly(page: Page) {
  await page.fill("#pinfl", "12345678901234");
  const devMockBtn = page.getByRole("button", { name: "Verify (dev mock)" });
  await expect(devMockBtn).toBeVisible({ timeout: 15_000 });
  await devMockBtn.click();
  await expect(page.locator("#fullNameOfficial")).toBeVisible({ timeout: 10_000 });
}

export async function completeKycStep(page: Page) {
  await verifyKycOnly(page);
  const continueBtn = page.getByRole("button", {
    name: /Saqlash va davom etish|Save & continue|Сохранить и продолжить|Continue/i,
  });
  await expect(continueBtn).toBeEnabled({ timeout: 10_000 });
  await continueBtn.click();
  await expect(page.locator("h2")).toContainText(/Ferma profili|Профиль фермера|Farm Profile/, {
    timeout: 20_000,
  });
}

export async function completeFarmProfileStep(page: Page) {
  await page.fill("#fullName", "Test Farmer");
  await page.selectOption("#gender", "male");
  await page.selectOption("#region", "tashkent_region");
  await expect(page.locator("#district option[value='zangiota']")).toBeAttached({ timeout: 10_000 });
  await page.selectOption("#district", "zangiota");
  await page.selectOption("#farmerType", "owner");
  await page.selectOption("#education", "secondary");
  await page.fill("#householdSize", "5");
  await page.fill("#yearsFarming", "10");
  await clickSaveContinue(page);
  await expect(page.locator("h2")).toContainText(/Yer ma'lumotlari|Информация о земле/, {
    timeout: 20_000,
  });
}

export async function completeLandSketchStep(page: Page) {
  const parcel = page.locator(".rounded-xl.border").first();
  const districtSelect = parcel.locator("select").first();
  if ((await districtSelect.inputValue()) !== "zangiota") {
    await districtSelect.selectOption("zangiota");
  }
  // Village (first textbox); cadastral number is the second optional textbox
  await parcel.getByRole("textbox").first().fill("Test Village");
  await parcel.locator('input[type="number"]').first().fill("2.5");
  await clickSaveContinue(page);
  await expect(page.locator("h2")).toContainText(/GIS|GIS-картирование/, { timeout: 20_000 });
}

export async function completeGisMappingStep(page: Page) {
  await page.fill("#gis-lat", "41.3111");
  await page.fill("#gis-lng", "69.2797");
  await clickSaveContinue(page);
  await expect(page.locator("h2")).toContainText(/Ekin|План культур/, { timeout: 20_000 });
}

export async function completeCropPlanStep(page: Page) {
  const cropCard = page.locator(".rounded-xl.border").filter({ hasText: /Ekin 1|Культура 1/ });
  await cropCard.locator("select").first().selectOption("cotton");
  const numbers = cropCard.locator('input[type="number"]');
  await numbers.nth(0).fill("2");
  await numbers.nth(1).fill("5");
  await clickSaveContinue(page);
  await expect(page.locator("h2")).toContainText(/Ferma aktivlari|Активы фермы/, {
    timeout: 20_000,
  });
}

export async function completeFarmAssetsStep(page: Page) {
  const assetCard = page.locator(".rounded-xl.border").filter({ hasText: /Aktiv 1|Актив 1/ });
  await assetCard.locator("select").first().selectOption("tractor");
  await clickSaveContinue(page);
  await expect(page.locator("h2")).toContainText(/Hujjatlar|Пакет документов/, {
    timeout: 20_000,
  });
}

export async function completeDocumentsStep(page: Page) {
  const fixtureDir = path.resolve(process.cwd(), "e2e/fixtures");
  const fixture = path.join(fixtureDir, "sample-doc.pdf");

  for (const labelPart of ["Yer hujjati", "Bank ko'chirmasi"]) {
    const input = page.getByLabel(new RegExp(`Upload.*${labelPart}`, "i"));
    await expect(input).toBeVisible({ timeout: 10_000 });
    await input.setInputFiles(fixture);
    await expect(page.locator("text=Upload failed")).not.toBeVisible({ timeout: 15_000 });
  }

  await expect(page.getByText(/2 \/ 2.*majburiy|2 \/ 2.*обязательных/)).toBeVisible({
    timeout: 30_000,
  });

  await clickSaveContinue(page);
  await expect(page.locator("h2")).toContainText(/Moliyaviy|Финансовый/, { timeout: 20_000 });
}

export async function completeFinanceRequestStep(page: Page) {
  await page.selectOption("#purpose", "inputs");
  await page.fill("#amountUzs", "5000000");
  await page.getByRole("button", { name: /12 oy|12 мес/ }).click();
  // OCR prefill from bank statement — align income to avoid review conflicts
  const income = page.locator("#monthlyIncomeUzs");
  if (await income.isVisible()) {
    await income.fill("10750000");
  }
  await clickSaveContinue(page);
  await expect(page.locator("h2")).toContainText(/Ko'rib chiqish|Проверка и отправка/, {
    timeout: 20_000,
  });
}

export async function completeReviewStep(page: Page) {
  const conflictBtn = page.getByRole("button", { name: /Mening ma'lumotimni saqlash|Оставить мои данные/ });
  if (await conflictBtn.first().isVisible().catch(() => false)) {
    const count = await conflictBtn.count();
    for (let i = 0; i < count; i++) {
      await conflictBtn.nth(i).click();
    }
  }

  await page.locator("label:has(input[type='checkbox'])").last().check();
  await page.getByRole("button", { name: /Arizani yuborish|Отправить заявку/ }).click();
  await expect(page.locator("h2")).toContainText(/qayta ishlanmoqda|Baholash|обрабатывается/, {
    timeout: 30_000,
  });
}

export async function completeScoringStep(page: Page) {
  // Scoring polls then auto-advances to RESULT — wait for outcome heading, not interim "complete" copy.
  await expect(page.locator("h2")).toContainText(
    /Siz mos kelasiz|Вы подходите|You are eligible|Shartli moslik|Conditional eligibility|Not eligible|Mos emas|Не подходите/i,
    { timeout: 90_000 },
  );
}

export async function completeResultStep(page: Page) {
  await expect(page.locator("h2")).toContainText(
    /Siz mos kelasiz|Вы подходите|You are eligible|Shartli moslik|Conditional eligibility|Not eligible|Mos emas|Не подходите/i,
    { timeout: 10_000 },
  );
  await page.getByRole("button", { name: /Kirish sahifasiga|На страницу входа|Go to login/i }).click();
  await page.waitForURL("**/farmers/login?registered=1");
  await expect(page.locator("text=Registration complete")).toBeVisible();
}

/** Log in on /farmers/login after completing the wizard. */
export async function loginAfterWizard(page: Page, phone: string) {
  if (page.url().includes("/farmers/dashboard")) {
    return;
  }

  if (!page.url().includes("/farmers/login")) {
    await page.goto("/farmers/login");
  }

  await page.fill("#login-phone", phone);
  await page.getByRole("button", { name: "Send Verification Code" }).click();
  await page.fill("#login-otp", DEV_OTP);
  await page.getByRole("button", { name: "Log In" }).click();
  await page.waitForURL("**/farmers/dashboard", { timeout: 30_000 });
}

/** Log in as a seeded demo farmer (PLAYWRIGHT=1 / dev mock). */
export async function loginAsDemoFarmer(page: Page, phone: string) {
  await page.goto("/farmers/login");
  await page.fill("#login-phone", phone);
  await page.getByRole("button", { name: "Send Verification Code" }).click();
  await page.fill("#login-otp", DEV_OTP);
  await page.getByRole("button", { name: "Log In" }).click();
  await page.waitForURL("**/farmers/dashboard**", { timeout: 30_000 });
}

/** Dashboard hub heading — locale-aware (default locale is uz). */
export const DASHBOARD_MODULES = /Your Farm Modules|Ferma modullari|Модули фермы/;
export const AGNET_FINANCE = /AGNET Finance|AGNET Moliya|AGNET Финансы/;
export const AGNET_TRADE = /AGNET Trade|AGNET Savdo|AGNET Торговля/;
export const AGNET_IDENTITY = /AGNET Identity|AGNET Identifikatsiya|AGNET Идентификация/;
export const AGNET_INPUTS = /AGNET Inputs|AGNET Resurslar|AGNET Ресурсы/;
export const WELCOME_BACK = /Welcome back|Xush kelibsiz|Добро пожаловать/;

/** Walk through all 13 onboarding wizard steps end-to-end. */
export async function completeFullWizard(page: Page, phone: string) {
  await authenticateViaApply(page, phone);
  await completeAccountStep(page, phone);
  await completeConsentStep(page);
  await completeKycStep(page);
  await completeFarmProfileStep(page);
  await completeLandSketchStep(page);
  await completeGisMappingStep(page);
  await completeCropPlanStep(page);
  await completeFarmAssetsStep(page);
  await completeDocumentsStep(page);
  await completeFinanceRequestStep(page);
  await completeReviewStep(page);
  await completeScoringStep(page);
  await completeResultStep(page);
}
