import { test, expect } from "@playwright/test";
import {
  authenticateViaApply,
  completeAccountStep,
  completeConsentStep,
  completeFullWizard,
  uniqueTestPhone,
  DEV_OTP,
  loginAfterWizard,
  verifyKycOnly,
  DASHBOARD_MODULES,
  AGNET_FINANCE,
  WELCOME_BACK,
} from "../helpers/wizard";

test.describe("Farmer Onboarding Wizard", () => {
  test("full wizard: apply through all steps to dashboard", async ({ page }) => {
    const phone = uniqueTestPhone();
    await completeFullWizard(page, phone);
    await page.waitForURL("**/farmers/dashboard", { timeout: 20_000 });
    await expect(page.getByText(DASHBOARD_MODULES)).toBeVisible({ timeout: 20_000 });
  });

  test("completed session redirects away from /farmers/onboarding", async ({ page }) => {
    const phone = uniqueTestPhone();
    await completeFullWizard(page, phone);
    await loginAfterWizard(page, phone);
    await page.goto("/farmers/onboarding");
    await page.waitForURL("**/farmers/dashboard", { timeout: 20_000 });
  });

  test("authenticated completed user on login?registered=1 redirects to dashboard", async ({ page }) => {
    const phone = uniqueTestPhone();
    await completeFullWizard(page, phone);
    await page.waitForURL("**/farmers/dashboard", { timeout: 20_000 });
  });

  test("farmer can defer wizard after KYC and resume from dashboard", async ({ page }) => {
    const phone = uniqueTestPhone();
    await authenticateViaApply(page, phone);
    await completeAccountStep(page, phone);
    await completeConsentStep(page);
    await verifyKycOnly(page);
    await page.getByRole("button", { name: /Finish later/i }).click();
    await page.waitForURL("**/farmers/dashboard", { timeout: 20_000 });
    await page.getByTestId("continue-application").click();
    await page.waitForURL("**/farmers/onboarding", { timeout: 20_000 });
    await expect(page.locator("h2")).toContainText(/Ferma profili|Farm Profile|Профиль фермера/, {
      timeout: 20_000,
    });
  });

  test("new user can start onboarding from /farmers/apply", async ({ page }) => {
    const phone = uniqueTestPhone();
    await authenticateViaApply(page, phone);
    await expect(page.locator("h2")).toContainText("Create your account");
  });

  test("resume: leaving mid-flow and returning resumes at same step", async ({ page }) => {
    const phone = uniqueTestPhone();
    await authenticateViaApply(page, phone);
    await completeAccountStep(page, phone);

    await page.goto("/");

    await page.goto("/farmers/onboarding");
    await expect(page.locator("text=Loading your application...")).toBeHidden({
      timeout: 20_000,
    });

    await expect(page.locator("h2")).toContainText(/Rozilik|Согласие|Consent/, { timeout: 20_000 });
  });

  test("login page is reachable after onboarding", async ({ page }) => {
    await page.goto("/farmers/login");
    await expect(page.locator("h1")).toBeVisible();
    await expect(page.locator("#login-phone")).toBeVisible();
  });

  test("login page shows registration success banner when redirected", async ({ page }) => {
    await page.goto("/farmers/login?registered=1");
    await expect(page.locator("text=Registration complete")).toBeVisible();
    await expect(page.locator("h1")).toContainText("Welcome to AGNET");
  });

  test("/farmers/apply page has correct structure", async ({ page }) => {
    await page.goto("/farmers/apply");

    await expect(page.locator("img[alt='AgNet Global']")).toBeVisible();
    await expect(page.locator("#apply-phone")).toBeVisible();
    await expect(page.locator("button:has-text('Send Verification Code')")).toBeVisible();
    await expect(page.locator("text=begin or resume your pilot application")).toBeVisible();
  });

  test("re-signup: completed user can start fresh via /farmers/apply", async ({ page }) => {
    await page.goto("/farmers/apply");

    await expect(page.locator("#apply-phone")).toBeVisible();

    await page.goto("/farmers/login");
    await expect(page.locator("a[href='/farmers/apply']")).toBeVisible();
    await expect(page.locator("text=Apply for the pilot")).toBeVisible();
  });
});

test.describe("Farmer Dashboard", () => {
  test("unauthenticated access redirects to login", async ({ page }) => {
    await page.goto("/farmers/dashboard");
    await page.waitForURL("**/farmers/login**");
    await expect(page.locator("#login-phone")).toBeVisible();
  });

  test("authenticated farmer with in-progress session is redirected to onboarding", async ({ page }) => {
    const phone = uniqueTestPhone();

    await page.goto("/farmers/apply");
    await page.fill("#apply-phone", phone);
    await page.click("button:has-text('Send Verification Code')");
    await page.fill("#apply-otp", DEV_OTP);
    await page.click("button:has-text('Continue to Application')");
    await page.waitForURL("**/farmers/onboarding");

    await page.goto("/farmers/dashboard");
    await page.waitForURL("**/farmers/onboarding**", { timeout: 20_000 });
    await expect(page.locator("h2")).toContainText(/Create your account|Rozilik|Согласие/, {
      timeout: 20_000,
    });
  });

  test("completed farmer can access dashboard", async ({ page }) => {
    const phone = uniqueTestPhone();
    await completeFullWizard(page, phone);

    await loginAfterWizard(page, phone);
    await expect(page.locator("h1")).toContainText(WELCOME_BACK, { timeout: 20_000 });
  });

  test("dashboard shows application status for completed farmers", async ({ page }) => {
    const phone = uniqueTestPhone();
    await completeFullWizard(page, phone);

    await loginAfterWizard(page, phone);

    await expect(page.getByText(DASHBOARD_MODULES)).toBeVisible({ timeout: 20_000 });
    await expect(page.getByText(/Eligible|Mos|Подходите/i)).toBeVisible();
    await expect(page.getByText("Score", { exact: true })).toBeVisible();
    await expect(page.getByText(AGNET_FINANCE)).toBeVisible();
  });

  test("login redirects authenticated user to dashboard", async ({ page }) => {
    const phone = uniqueTestPhone();

    await page.goto("/farmers/apply");
    await page.fill("#apply-phone", phone);
    await page.click("button:has-text('Send Verification Code')");
    await page.fill("#apply-otp", DEV_OTP);
    await page.click("button:has-text('Continue to Application')");
    await page.waitForURL("**/farmers/onboarding");

    await page.goto("/farmers/login");
    await page.waitForURL("**/farmers/**", { timeout: 10_000 });
  });
});

test.describe("Document Upload", () => {
  test("GIS mapping step shows coordinate inputs", async ({ page }) => {
    const phone = uniqueTestPhone();
    await authenticateViaApply(page, phone);

    await page.goto("/farmers/onboarding");
    await expect(page.locator("text=Loading your application...")).toBeHidden({
      timeout: 20_000,
    });

    await expect(page.locator("#gis-lat")).not.toBeVisible();
  });

  test("StepResult shows dashboard CTA", async ({ page }) => {
    const phone = uniqueTestPhone();
    await completeFullWizard(page, phone);

    await page.goBack();
    await expect(page.locator("a:has-text('Go to Dashboard')")).toBeVisible({ timeout: 5_000 }).catch(() => {
      // May have navigated past result step
    });
  });
});
