const { chromium } = require("playwright");
const { randomUUID } = require("crypto");

(async () => {
  console.log("🎭 Starting Live UI Testing Demo\n");

  const testEmail = `testcompany${randomUUID().slice(0, 8)}@test.com`;
  const testPassword = "TestPassword123!";
  const testCompanyName = `Test Company ${randomUUID().slice(0, 6)}`;
  const firstName = "John";
  const lastName = "Doe";

  console.log("📧 Test Email:", testEmail);
  console.log("👤 Name:", firstName, lastName);
  console.log("🏢 Company Name:", testCompanyName);
  console.log("\n🚀 Launching Chromium browser with visible window...\n");

  const browser = await chromium.launch({
    headless: false,
    slowMo: 800,
    args: ["--window-size=1400,900"],
  });

  const context = await browser.newContext({
    viewport: { width: 1400, height: 900 },
  });

  const page = await context.newPage();

  try {
    // Step 1: Navigate to signup
    console.log("📍 Step 1: Opening signup page...");
    await page.goto("http://localhost:3001/signup?intent=company");
    await page.waitForTimeout(3000);

    // Step 2: Fill ALL required fields
    console.log("✍️  Step 2: Filling ALL required fields...\n");

    // First Name
    console.log("   → First Name...");
    const firstNameInput = await page
      .locator('input[name="firstName"], input[placeholder*="First"]')
      .first();
    await firstNameInput.fill(firstName);
    await page.waitForTimeout(500);

    // Last Name
    console.log("   → Last Name...");
    const lastNameInput = await page
      .locator('input[name="lastName"], input[placeholder*="Last"]')
      .first();
    await lastNameInput.fill(lastName);
    await page.waitForTimeout(500);

    // Email
    console.log("   → Email...");
    const emailInput = await page
      .locator('input[type="email"], input[name="email"]')
      .first();
    await emailInput.fill(testEmail);
    await page.waitForTimeout(500);

    // Password
    console.log("   → Password...");
    const passwordInput = await page.locator('input[name="password"]').first();
    await passwordInput.fill(testPassword);
    await page.waitForTimeout(500);

    // Confirm Password
    console.log("   → Confirm Password...");
    const confirmInput = await page
      .locator('input[name="confirmPassword"], input[name="confirm"]')
      .first();
    await confirmInput.fill(testPassword);
    await page.waitForTimeout(500);

    // CAPTCHA - Read the code from the canvas/image
    console.log("   → Reading CAPTCHA code...");
    const captchaText = await page
      .locator(".captcha-code, [data-captcha], .captcha-display")
      .textContent()
      .catch(() => null);
    if (captchaText) {
      console.log("   → CAPTCHA found:", captchaText.trim());
      const captchaInput = await page
        .locator('input[name="captcha"], input[placeholder*="CAPTCHA"]')
        .first();
      await captchaInput.fill(captchaText.trim());
    } else {
      console.log("   → CAPTCHA not readable, will try to find input...");
      // Try to get from a data attribute or regenerate
      const captchaInput = await page.locator('input[name="captcha"]').first();
      if (captchaInput) {
        // Look for any visible captcha text
        const captchaCode = await page.evaluate(() => {
          const el = document.querySelector(
            ".captcha-code, .captcha-text, [data-captcha]",
          );
          return el ? el.textContent || el.getAttribute("data-captcha") : null;
        });
        if (captchaCode) {
          await captchaInput.fill(captchaCode.trim());
          console.log("   → CAPTCHA filled:", captchaCode.trim());
        }
      }
    }
    await page.waitForTimeout(500);

    // Terms Checkbox
    console.log("   → Checking Terms & Conditions...");
    const termsCheckbox = await page
      .locator(
        'input[type="checkbox"][name*="terms"], input[type="checkbox"][name*="agree"]',
      )
      .first();
    if (termsCheckbox) {
      await termsCheckbox.check();
      console.log("   ✅ Terms checkbox checked");
    }
    await page.waitForTimeout(500);

    console.log("\n✅ All fields filled!");
    await page.waitForTimeout(2000);

    // Step 3: Submit signup
    console.log("\n📤 Step 3: Clicking Sign Up button...");
    const submitBtn = await page
      .locator(
        'button[type="submit"]:has-text("Sign"), button:has-text("Create"), button:has-text("Register")',
      )
      .first();

    // Check if button is enabled
    const isDisabled = await submitBtn.isDisabled().catch(() => false);
    if (isDisabled) {
      console.log("⚠️  Button is disabled - checking what field is missing...");
      // Take screenshot to debug
      await page.screenshot({
        path: "./test-results/signup-debug.png",
        fullPage: true,
      });
    } else {
      await submitBtn.click();
      console.log("✅ Sign Up button clicked");
    }
    await page.waitForTimeout(5000);

    // Step 4: Check current page
    const currentUrl = page.url();
    console.log("\n📍 Current URL:", currentUrl);

    if (currentUrl.includes("verify") || currentUrl.includes("otp")) {
      console.log("📧 Step 4: OTP verification page detected");
      console.log("   → Entering OTP...");

      // Fill OTP (6 digits)
      const otpDigits = ["1", "2", "3", "4", "5", "6"];
      for (let i = 0; i < 6; i++) {
        const otpInput = await page
          .locator(`input[name="otp${i}"], input[aria-label*="digit ${i + 1}"]`)
          .first();
        if (otpInput) {
          await otpInput.fill(otpDigits[i]);
          await page.waitForTimeout(200);
        }
      }

      // Submit OTP
      const verifyBtn = await page
        .locator('button:has-text("Verify"), button[type="submit"]')
        .first();
      await verifyBtn.click();
      console.log("✅ OTP submitted");
      await page.waitForTimeout(4000);
    }

    // Step 5: Select Company role if on role selection page
    console.log("\n🎯 Step 5: Checking for role selection...");
    const roleOption = await page.locator("text=Company").first();
    if (await roleOption.isVisible().catch(() => false)) {
      await roleOption.click();
      console.log("✅ Company role selected");
      await page.waitForTimeout(3000);
    }

    // Step 6: Fill Company Profile
    console.log("\n📝 Step 6: Filling company profile...");

    // Company name
    const nameInputs = await page
      .locator(
        'input[name*="company"], input[name*="name"], input[placeholder*="Company"]',
      )
      .all();
    for (const input of nameInputs.slice(0, 3)) {
      try {
        const placeholder = await input.getAttribute("placeholder");
        const name = await input.getAttribute("name");

        if (
          placeholder?.toLowerCase().includes("company") ||
          name?.toLowerCase().includes("company")
        ) {
          await input.fill(testCompanyName);
          console.log("   ✅ Company name:", testCompanyName);
          break;
        }
      } catch (e) {}
    }
    await page.waitForTimeout(1000);

    // Fill other profile fields
    const inputs = await page.locator("input, textarea, select").all();
    for (const input of inputs) {
      try {
        const type = await input.getAttribute("type");
        const name = await input.getAttribute("name");
        const tagName = await input.evaluate((el) => el.tagName.toLowerCase());

        if (tagName === "select") {
          // Select dropdown
          const options = await input.locator("option").all();
          if (options.length > 1) {
            await input.selectOption({ index: 1 });
          }
        } else if (type === "email" || name?.includes("email")) {
          await input.fill(testEmail);
        } else if (name?.includes("phone") || name?.includes("contact")) {
          await input.fill("+91 9876543210");
        } else if (name?.includes("city")) {
          await input.fill("Bangalore");
        } else if (name?.includes("state")) {
          await input.fill("Karnataka");
        } else if (name?.includes("country")) {
          await input.fill("India");
        } else if (name?.includes("address")) {
          await input.fill("123 Tech Park, Bangalore");
        } else if (name?.includes("website")) {
          await input.fill("https://testcompany.com");
        } else if (name?.includes("industry")) {
          await input.fill("Technology");
        } else if (name?.includes("description") || name?.includes("about")) {
          await input.fill(
            "We are a technology company looking for talented professionals to join our team. We offer competitive salaries and a great work environment.",
          );
        } else if (type === "text" && !name?.includes("name")) {
          // Fill any empty text fields
          const value = await input.inputValue();
          if (!value) {
            await input.fill("Test Data");
          }
        }
      } catch (e) {}
    }
    console.log("   ✅ Profile fields filled");
    await page.waitForTimeout(2000);

    // Step 7: Submit for verification
    console.log("\n🚀 Step 7: Submitting profile for verification...");
    const profileSubmitBtn = await page
      .locator(
        'button[type="submit"], button:has-text("Submit"), button:has-text("Save"), button:has-text("Continue")',
      )
      .first();
    await profileSubmitBtn.click();
    console.log("✅ Profile submitted");
    await page.waitForTimeout(5000);

    // Take screenshot
    await page.screenshot({
      path: "./test-results/after-profile-submit.png",
      fullPage: true,
    });
    console.log("📸 Screenshot saved: after-profile-submit.png");

    // Step 8: Open Admin Panel in new tab
    console.log("\n🔐 Step 8: Opening admin panel...");
    const adminPage = await context.newPage();
    await adminPage.goto("http://localhost:3000/login");
    await adminPage.waitForTimeout(3000);

    // Admin login
    console.log("🔑 Logging into admin panel...");
    const adminEmailInput = await adminPage
      .locator('input[type="email"], input[name="email"]')
      .first();
    await adminEmailInput.fill("admin@nxtgauge.com");
    await adminPage.waitForTimeout(500);

    const adminPasswordInput = await adminPage
      .locator('input[type="password"]')
      .first();
    await adminPasswordInput.fill("admin123");
    await adminPage.waitForTimeout(500);

    const adminLoginBtn = await adminPage
      .locator('button[type="submit"]')
      .first();
    await adminLoginBtn.click();
    console.log("✅ Admin login submitted");
    await adminPage.waitForTimeout(4000);

    // Step 9: Navigate to Verifications
    console.log("\n🔍 Step 9: Navigating to Verification Management...");
    await adminPage.goto("http://localhost:3000/admin/verification");
    await adminPage.waitForTimeout(4000);

    // Step 10: Search for the company
    console.log("\n🔎 Step 10: Searching for submitted company...");
    const searchInput = await adminPage
      .locator(
        'input[type="search"], input[name="search"], input[placeholder*="search"]',
      )
      .first();
    if (searchInput) {
      await searchInput.fill(testCompanyName);
      console.log(`   ✅ Searching for: ${testCompanyName}`);
      await adminPage.waitForTimeout(3000);
    }

    // Take final screenshot
    await adminPage.screenshot({
      path: "./test-results/admin-verification.png",
      fullPage: true,
    });
    console.log("📸 Screenshot saved: admin-verification.png");

    // Check if company is found
    const companyFound = await adminPage
      .locator(`text=${testCompanyName}`)
      .isVisible()
      .catch(() => false);
    if (companyFound) {
      console.log(
        "\n✅ SUCCESS! Company verification request found in admin panel!",
      );
      console.log(`   Company: ${testCompanyName}`);
      console.log(`   Email: ${testEmail}`);
    } else {
      console.log("\n⚠️  Company not immediately visible. Check:");
      console.log("   - Filters may need adjustment");
      console.log("   - Verification may still be processing");
      console.log("   - Try searching by email instead");
    }

    console.log("\n⏳ Keeping browser open for 20 seconds...");
    console.log("   Screenshots saved in ./test-results/");
    await new Promise((resolve) => setTimeout(resolve, 20000));
  } catch (error) {
    console.error("\n❌ Error:", error.message);
    await page.screenshot({ path: "./test-results/error.png", fullPage: true });
  } finally {
    await context.close();
    await browser.close();
    console.log("\n✅ Test completed");
  }
})();
