import { Page } from "@playwright/test";
import { test, expect, ACCOUNT } from "../../../src/fixture/base-test";
import { TIMEOUT } from "../../../src/constant/timeout";
import { PW } from "../../../src/utils/PW";
import { uc77DefaultData, uc77DefaultUrl } from "../uc77.default.data";

const BASE_URL = process.env.BASE_URL!;

const EXPECTED_COLUMNS = [
  "Tên hồ sơ/tài liệu",
  "Kế thừa",
  "Quyền Owner",
  "Quyền tạo mới",
  "Quyền cập nhật",
  "Quyền tải file",
  "Quyền xem",
];

const checkPhanQuyenNangCaoModal = async (userPage: Page, label: string) => {
  const trigger = userPage.getByTestId("btn-more");
  await expect(trigger, {
    message: `[${label}] Lỗi: Không tìm thấy nút btn-more trên title modal`,
  }).toBeVisible({ timeout: TIMEOUT.CONTROL_LOADING });
  await trigger.hover();
  await expect(userPage.getByTestId("btn-kiem-tra-phan-quyen"), {
    message: `[${label}] Lỗi: Không hiển thị button 'Kiểm tra phân quyền'`,
  }).toBeVisible({ timeout: TIMEOUT.CONTROL_LOADING });
  await userPage.getByTestId("btn-kiem-tra-phan-quyen").click();
  await userPage.waitForTimeout(TIMEOUT.DATA_LOADING);

  await expect(userPage.getByTestId("lbl-modal-title"), {
    message: `[${label}] Lỗi: Title modal không phải 'Phân quyền nâng cao'`,
  }).toContainText("Phân quyền nâng cao", { timeout: TIMEOUT.CONTROL_LOADING });

  await expect(userPage.getByText("Theo phân quyền"), {
    message: `[${label}] Lỗi: Không hiển thị nút 'Theo phân quyền'`,
  }).toBeVisible({ timeout: TIMEOUT.CONTROL_LOADING });
  await expect(userPage.getByText("Theo người dùng"), {
    message: `[${label}] Lỗi: Không hiển thị nút 'Theo người dùng'`,
  }).toBeVisible({ timeout: TIMEOUT.CONTROL_LOADING });

  const modalContent = userPage.locator(".ant-modal-content").last();
  await expect(
    modalContent.locator('input[placeholder="Tìm hồ sơ, tài liệu"]'),
    { message: `[${label}] Lỗi: Không tìm thấy ô input 'Tìm hồ sơ, tài liệu'` },
  ).toBeVisible({ timeout: TIMEOUT.CONTROL_LOADING });

  const thTexts = await modalContent
    .locator(".ant-table-thead th")
    .allTextContents();
  const nonEmptyThs = thTexts.map((t) => t.trim()).filter((t) => t !== "");
  for (const col of EXPECTED_COLUMNS) {
    expect(nonEmptyThs, {
      message: `[${label}] Lỗi: Không tìm thấy cột '${col}' trong bảng phân quyền`,
    }).toContain(col);
  }
};
const addFolderCauTrucHoSo = async (userPage: Page, pwUser: PW) => {
  await userPage.getByTestId("lbl-tab-cauTrucHoSo").click();
  await userPage
    .locator(".ant-modal-content")
    .last()
    .locator("button span")
    .filter({ hasText: /^Tạo mới$/ })
    .click();

  const folderModal = userPage.locator(".ant-modal-content").last();

  await folderModal
    .locator('input[type="text"][placeholder="Nhập tên"]')
    .fill("Thư mục A");

  if (await folderModal.getByTestId("tree-sel-submissionUnit").isVisible()) {
    await pwUser.inputTreeDropDown("tree-sel-submissionUnit");
  }

  const uniqueCheckbox = folderModal.locator('input#uniquePermission[type="checkbox"]');
  if (await uniqueCheckbox.isVisible()) {
    await uniqueCheckbox.check();
  } else {
    await folderModal
      .locator(".ant-tabs-nav-list .ant-tabs-tab")
      .filter({ hasText: "Phân quyền" })
      .click();
    await folderModal
      .locator(".ant-alert-action")
      .getByRole("button", { name: "Đặt quyền độc lập" })
      .click();
  }

  const peoplePicker = folderModal.locator(".people-picker").first();
  await peoplePicker.click();
  await peoplePicker.locator("input").fill("ecm06");
  await userPage.waitForTimeout(5000);
  await peoplePicker.locator("input").press("Enter");

  await folderModal.getByRole("button", { name: /Lưu/ }).click();

  await expect(userPage.locator(".ant-message-notice"), {
    message: "Lỗi: Thông báo 'Thành công' sau Tạo thư mục không hiển thị",
  }).toContainText("Thành công", { timeout: TIMEOUT.ACTION_LOADING });
};
const addDocumentCauTrucHoSo = async (userPage: Page, pwUser: PW) => {
  await userPage.getByTestId("lbl-tab-cauTrucHoSo").click();

  const cauTrucModal = userPage.locator(".ant-modal-content").last();
  await cauTrucModal.locator(".ant-dropdown-trigger").hover();
  await userPage
    .locator("li.ant-dropdown-menu-item")
    .filter({ hasText: "Tài liệu" })
    .click();

  await userPage.waitForTimeout(10000);

  const docModal = userPage.locator(".ant-modal-content").last();
  await docModal.locator('[data-testid="txt-ten-tai-lieu"]').fill("Tài liệu B");
  await pwUser.inputDropDownList("sel-loai-tai-lieu");
  await docModal.locator("input#basic_hasUniquePermission").check();
  await pwUser.inputPeoplePicker("pp-multi-usersRightOwner", "ecm07");
  await pwUser.clickButton("btn-save");

  await expect(userPage.locator(".ant-message-notice"), {
    message: "Lỗi: Thông báo 'Thành công' sau Tạo tài liệu không hiển thị",
  }).toContainText("Thành công", { timeout: TIMEOUT.ACTION_LOADING });
};
test(
  "UC77,78,80 1.2.1.89 - Kiểm tra màn hình thông tin phân quyền bộ hồ sơ" +
    ACCOUNT.ADMIN,
  async ({ admin, ecm05, librarian, ecm06, ecm07 }) => {
    const pw = new PW(admin);
    const uniqueName = `AT-UC77-89-${Date.now()}`;

    await test.step("1. Admin tạo mới hồ sơ và gán quyền Owner cho ecm05", async () => {
      await admin.goto(`${BASE_URL}${uc77DefaultUrl}`);
      await pw.isVisible("btn-create-hstl", TIMEOUT.PAGE_LOADING);
      await pw.wait(TIMEOUT.HARD_WAITING);
      await pw.clickButton("btn-create-hstl");
      await pw.batchInput(
        uc77DefaultData.filter(
          (o) =>
            !o.testId.startsWith("pp-multi-") &&
            o.testId !== "txt-tenHoSo" &&
            o.testId !== "btn-add-related-ecm",
        ),
        true,
      );
      await pw.inputText("txt-tenHoSo", uniqueName);
      await pw.inputPeoplePicker("pp-multi-usersRightOwner", "ecm05");
      await pw.clickButton("btn-save");
      await expect(admin.locator(".ant-message-success"), {
        message: "Lỗi: Tạo mới hồ sơ không thành công",
      }).toBeVisible({ timeout: TIMEOUT.ACTION_LOADING });
      await pw.wait(TIMEOUT.ACTION_LOADING);
    });

    const recordUrl = admin.url();

    const ROLE_CHECKS = [
      { userPage: admin, label: "Admin (ecm09)" },
      { userPage: ecm05, label: "ecm05 Owner" },
      { userPage: librarian, label: "ecm01 Thủ thư" },
      { userPage: ecm06, label: "ecm06 Owner Thư mục" },
      { userPage: ecm07, label: "ecm07 Owner Tài liệu" },
    ];

    await test.step("2–4. Kiểm tra nội dung modal 'Phân quyền nâng cao' theo từng vai", async () => {
      for (const { userPage, label } of ROLE_CHECKS) {
        await test.step(`Kiểm tra [${label}]`, async () => {
          const pwUser = new PW(userPage);
          await userPage.goto(recordUrl);
          await pwUser.wait(TIMEOUT.HARD_WAITING);
          await addFolderCauTrucHoSo(userPage, pwUser);
          await addDocumentCauTrucHoSo(userPage, pwUser);
          await checkPhanQuyenNangCaoModal(userPage, label);
        });
      }
    });
  },
);
