import { DashboardPage } from "../dashboard.page";
import { Browser, BrowserContext, expect, Page } from '@playwright/test'
import { tableSearchUniqueSnapshot, headingAndCreateButton, tipsBlock, emptyState, haveRecord, caseUpdateUIHeader, caseUpdateUIBody, caseUpdateUIFooter, caseDetailLackInfo, caseDetailFullInfo } from "./case.snapshot";
import { LoginPage } from "../login.page";
import { RequestPage } from "../request/request.page";

export class CasePage extends DashboardPage {
    personalSearch: `//input[@class='form-control' and @placeholder='Search...']` | undefined;

    constructor(page: Page) {
        super(page);
    }

    actionType = [
        { name: "Letter of Protection", expectedRequests: 2 },
        { name: "Medical Bill", expectedRequests: 1 },
        { name: "Prescription", expectedRequests: 1 },
        { name: "Others", expectedRequests: 1 },
        { name: "Transfer", expectedRequests: 1 }
    ]

    statusTests = [
        { detail: 'Open', expectedStatus: 'Open' },
        { detail: 'In Progress', expectedStatus: 'In Progress' },
        { detail: 'On Hold', expectedStatus: 'On Hold' },
        { detail: 'Closed', expectedStatus: 'Closed' },
        { detail: 'Dropped', expectedStatus: 'Closed' },
        { detail: 'Cancelled', expectedStatus: 'Closed' },
        { detail: 'Declined', expectedStatus: 'Closed' },
        { detail: 'Transferred', expectedStatus: 'Closed' },
        { detail: 'Referred', expectedStatus: 'Closed' },
        { detail: 'Unknown', expectedStatus: 'Unknown' }
    ];

    infoPrev = ["full_name_client", "birthday_client", "address_client", "email_client", "phone_client", "text-description-case"];

    caseUpdateForm = [
        {
            inputName: "service_from",
            type: "input",
        },
        {
            inputName: "service_to",
            type: "input",
        },
        {
            inputName: "reference_id",
            type: "input"
        },
        {
            inputName: "description",
            type: "textarea"
        },
    ]

    get caseProps() {
        return {
            filterProperties: [
                {
                    name: 'case_id',
                    type: 'input'
                },
                {
                    name: 'patient',
                    type: 'input'
                }
            ],
            threeDotDropdownMenus: {
                customizedColumn: 'Customized Columns',
            },
            requestsColumns: [
                {
                    name: '#',
                    default: true,
                    tableDisplayName: '#'
                },
                {
                    name: 'Request',
                    default: true,
                    tableDisplayName: 'Request'
                },
                {
                    name: 'Status',
                    default: true,
                    tableDisplayName: 'Status'
                },
                {
                    name: 'Status Details',
                    default: true,
                    tableDisplayName: 'Status Details'
                },
                {
                    name: 'Star It',
                    default: true,
                    tableDisplayName: 'Star It'
                },
                {
                    name: 'Patient Name',
                    default: false,
                    tableDisplayName: 'Patient Name'
                },
                {
                    name: 'Share From',
                    default: true,
                    tableDisplayName: 'Share From'
                },
                {
                    name: 'Creator',
                    default: true,
                    tableDisplayName: 'Creator'
                },
                {
                    name: 'Directed To',
                    default: true,
                    tableDisplayName: 'Directed To'
                },
                {
                    name: 'Submit User',
                    default: false,
                    tableDisplayName: 'Submitted User'
                },
                {
                    name: 'Date',
                    default: false,
                    tableDisplayName: 'Date'
                },
                {
                    name: 'Updated',
                    default: false,
                    tableDisplayName: 'Updated'
                },
                {
                    name: 'Actions',
                    default: true,
                    tableDisplayName: 'Actions'
                }

            ],
            customizedColumns: [
                {
                    name: 'Pin',
                    default: true,
                    tableDisplayName: 'Pin'
                },
                {
                    name: 'Case #',
                    default: true,
                    tableDisplayName: 'Case #'
                },
                {
                    name: 'Patient Name',
                    default: true,
                    tableDisplayName: 'Patient Name'
                },
                {
                    name: 'DOI',
                    default: true,
                    tableDisplayName: 'DOI'
                },
                {
                    name: 'Status',
                    default: true,
                    tableDisplayName: 'Status'
                },
                {
                    name: 'Client DOB',
                    default: false,
                    tableDisplayName: 'Client DOB'
                },
                {
                    name: 'Category',
                    default: false,
                    tableDisplayName: 'Category'
                },
                {
                    name: 'Service From',
                    default: false,
                    tableDisplayName: 'Service From'
                },
                {
                    name: 'Service To',
                    default: false,
                    tableDisplayName: 'Service To'
                },
                {
                    name: 'Alias',
                    default: false,
                    tableDisplayName: 'Alias'
                },
                {
                    name: 'Case Name',
                    default: false,
                    tableDisplayName: 'Case Name'
                },
                {
                    name: 'Assignee',
                    default: false,
                    tableDisplayName: 'Assignee'
                },
                {
                    name: 'Date',
                    default: false,
                    tableDisplayName: 'Date'
                },
                {
                    name: 'Updated',
                    default: false,
                    tableDisplayName: 'Updated'
                }
            ]
        }
    }

    checkboxArchiveList = [this.caseLoc.checkboxArchiveMe, this.caseLoc.checkboxArchiveTeam];

    get caseLoc() {
        return {
            // Case New
            itemBoldUnread: this.genLoc("//tr[contains(@class,'not_field_read fw-bold')]"),
            itemReaded: this.genLoc("//tr[contains(@class,'row-data-table read')]"),
            itemAcceptedButUnRead: this.genLoc("//tr[contains(@class,'row-data-table')]"),
            caseIDNew: (caseID: string) => this.genLoc(`//a[contains(.,'${caseID}')]/descendant::span[text()='${caseID}']`),

            shareRequest: {
                tableActivityRequest: this.genLoc("//h2[text()='Request Activity']//ancestor::div[contains(@class,'card bd-none bx-shadow')]"),
                cardCase: this.genLoc("//div[@class='card-body p-3']"),
                modalPromote: this.genLoc("//h2[text()='Enhance this Request?']/ancestor::div[contains(@class,'modal-body')]"),
                buttonPromote: this.genLoc("//div[@class='request-action-icon']"),
                tableShareRequest: this.genLoc("//div[contains(@class,'tips-content')]")
            },

            linkcase: {
                bannerNewBusinessAddon: this.genLoc("//div[contains(@class,'box-case-have-new-business-add-on')]"),
                newRequestID: this.genLoc("//div[contains(@class, 'card-header') and .//h2[text()='Request Activity']]//following-sibling::div[contains(@class, 'table-responsive')]/table/descendant::a[1]"),
                newCaseID: this.genLoc("//tr[contains(@class,'not_field_read fw-bold')]/td[2]/descendant::span"),
                bannerCreatedCaseSuccess: this.genLoc("//div[@class='case-confirm-banner']")
            },

            //Cart
            optionCartHoverCaseID: (option: string) => this.genLoc(`//span[@class='d-inline-block text-ellipsis' and text()='${option}']`),

            linkToCase: (caseID: string) => this.genLoc(`//span[contains(.,'#${caseID}')] | //a[contains(.,'#${caseID}')]`),
            linkToCaseID: (caseID: string) => this.genLoc(`//a[contains(text(),'#${caseID}')]`),
            btnCloseModal: this.genLoc("//button[text()='Close' and @data-user-tracking]"),
            checkboxArchiveMe: this.genLoc("//input[contains(@id,'checkbox-user_state#is_archived')]"),
            checkboxArchiveTeam: this.genLoc("//input[contains(@id,'checkbox-business_state#is_archived')]"),
            noCaseFound: this.genLoc("//div[@class='table-responsive table-fixed placeholder-glow']//div[contains(., 'Create a new case.') and .//span[contains(., 'Click here.')]]"),
            inputArchive: this.genLoc("//input[@name='is_archived']"),
            boxSelectArchive: (option: string) => this.genLoc(`//div[@class='autocomplete-option' and contains(.,'${option}')]`),
            create: {
                inputDOI: this.genLoc("//input[@id='date_time_date_of_injury']"),
                tagBusinessCreate: (businessName: string) => this.genLoc(`//div[contains(@class,'date-option') and contains(.,'${businessName}')]`),
                optionBusiness: (option: string) => this.genLoc(`//li[contains(.,'${option}')]`),
                header: this.genLoc("//h2[text()='New Patient']"),
                btnCreate: this.genLoc("//button[text()='Create']"),
                btnCreateCase: this.genLoc("//button[text()='Create Case']"),
                msgCreateSuccess: this.genLoc("//p[text()='Added New Successfully!']"),
                detail: {
                    noOptionsCategory: this.genLoc("//div[@class='no-options']"),
                    inputCreateClientName: (name: string) => this.genLoc(`//input[@name='${name}']`),
                    inputByPlaceHolder: (placeholder: string) => this.genLoc(`//input[@placeholder="${placeholder}"]`),
                    createActive: this.genLoc("//button[@class='dropdown-item' and contains(.,'Add')] "),
                    description: this.genLoc("//textarea[@name='description']"),
                    doi: this.genLoc("//input[@name='date_of_injury']"),
                    bussiness: this.genLoc("(//input[@placeholder='Select or type a name'])[2]"),
                    boxTextBusinessByName: (name: string) => this.genLoc(`//div[contains(@class,'box-text box-text-business')]/div[text()='${name}']`),
                    boxTextBusiness: this.genLoc("//div[contains(@class,'box-text box-text-business')]"),
                    categoryInput: this.genLoc("//input[@id='autocomplete_category_id']"),
                    inputCategory: this.genLoc("//div[@class='selectize-input items has-options not-full focus input-active dropdown-active']/input"),
                    labelBusiness: this.genLoc("//label[text()='Business']"),
                    optionCategory: (optionName: string) => this.genLoc(`//div[@class='title-option' and text()='${optionName}']`)
                },
                preview: {
                    infoClient: (name: string) => this.genLoc(`//p[contains(@class,'${name}')]`)
                }
            },
            detail: {
                createNewRequestWithNewCase: this.genLoc("//button[@data-test-id='btn-case-case-detail-new-request']"),
                btnSubmitAssignee: this.genLoc("//button[@data-test-id='btn-modal-assignee-member-submit']"),
                btnSubmitLegalContact: this.genLoc("//button[@data-test-id='btn-modal-legal-contact-case-detail-submit']"),
                btnCloseModalUpdate: this.genLoc("//button[@data-test-id='btn-modal-case-new-edit-cancel']"),
                requestTableNoResult: this.genLoc("//div[text()='Start your request today.']"),
                dataIntable: (tableName: string, caseID: string) => this.genLoc(`//h2[text()='${tableName}']/following::a[text()='${caseID}']`),
                dropdownOption: (action: string) => this.genLoc(`//span[@class='dropdown-item cursor-pointer' and text()='${action}']`),
                btnClosePopup: this.genLoc("//button[@class='my-snackbar__close']"),
                listBoxTag: this.genLoc("//div[@class='list-request-tag']"),
                clickAddTag: this.genLoc("//div[@class='create active']"),
                iconTag: this.genLoc("//div[@class='icon-request-tag']"),
                noDataRequest: this.genLoc("//div[contains(text(),'Start your request today.')]"),
                noLegal: this.genLoc("//a[@data-user-tracking='BTN_SHOW_LEGAL_CONTACTS_MODAL']"),
                businessContact: this.genLoc("//p[contains(@class,'business-contact-name')]"),
                buttonActivity: this.genLoc("//button[@data-user-tracking='BTN_SHOW_REQUEST_ACTIVITY_MODAL']"),
                buttonUpdateCase: this.genLoc("//button[@data-user-tracking='BTN_SHOW_UPDATE_CASE_MODAL']"),
                boxClientNameActive: (clientName: string) => this.genLoc(`//div[@class='box-text box-text-business' and contains(.,'${clientName}')]`),
                textNoRequest: this.genLoc("//p[contains(.,'to submit your request or inquiries for this case now!')]"),
                requestExist: (requestID: string) => this.genLoc(`//a[contains(text(),'${requestID}')]`),
                requestExitInRequestTable: (requestID: string) => this.genLoc(`//div[contains(@class, 'card-header') and .//h2[text()='Request Activity']]//following-sibling::div[contains(@class, 'table-responsive')]//table//tr[td/a[@href='/requests/${requestID}']]`),
                caseID: (caseID: string) => this.genLoc(`//span[text()='#${caseID}']`),
                discussionCase: this.genLoc("//div[contains(@class,'case-discussion-menu-icon')]/parent::div"),
                teamDiscussion: this.genLoc("//img[@alt='Team Discussion']"),

                existLegal: (nameClient: string) => this.genLoc(`//p[contains(., "${nameClient} case file is ready to go!")]`),
                discussion: {
                    inputMsg: this.genLoc("//input[@placeholder='Message']"),
                    contentMsg: (message: string) => this.genLoc(`//div[@class='content-message' and text()='${message}']`)
                },

                update: {
                    fieldForm: (type: string, name: string) => this.genLoc(`//${type}[@name='${name}']`),
                    btnUpdate: this.genLoc("//a[text()='Update']"),
                    inputDoi: this.genLoc('//input[@name="date_of_injury" and @value]'),
                    selectLawFirm: (name: string) => this.genLoc(`//input[@id='${name}']/ancestor::div[@class='autocomplete-control']/descendant::button[@class='clear-btn']`),
                    buttonSpan: (name: string) => this.genLoc(`//span[text()='${name}']`),
                    msgArchive: this.genLoc("//p[text()='This case has been archived']"),
                    msgUnArchive: this.genLoc("//p[text()='This case has been unarchived']"),
                    boxHeaderArchive: this.genLoc("//div[@class='box-notification-archive']"),
                    btnUnArchive: this.genLoc("//a[text()='unarchiving.']"),
                    btnCancel: this.genLoc("(//div[contains(@class,'modal-footer')]/descendant::a[text()='Cancel'])[1]")
                },
                activity: {
                    listActivity: this.genLoc("//div[@class='box-modal-activity-history activity-history']"),
                    buttonClose: this.genLoc("//div[@class='box-btn-reset-apply-filter']/button[text()='Close']")
                },
                addLegalModal: {
                    btnAddSuggest: (nameBusiness: string) => this.genLoc(`//p[contains(text(),'Add suggested:')]/span[text()='${nameBusiness}']`),
                    counselAdd: (email: string) => this.genLoc(`//span[@class="date-option" and text()="${email}"]`),
                    inputByPlaceholder: (placeholder: string) => this.genLoc(`//input[@placeholder="${placeholder}"]`),
                    btnSubmit: this.genLoc("//button[text()='Submit']"),
                    msgSuccess: this.genLoc("//p[text()='Updated Successfully!']")
                },
                transfer: {
                    inputTransfer: this.genLoc("(//input[@name='move_to_case_id'])[2]"),
                    boxOption: (value: string) => this.genLoc(`//div[@class='title-option' and contains(text(),'${value}')]/ancestor::div[@class='autocomplete-option']`),
                    buttonArchive: this.genLoc("//button[text()='Archive']"),
                    msgArchive: this.genLoc("//p[text()='This case has been archived']"),
                    radioCheckArchive: this.genLoc("//input[@id='radio-action-action2']")
                },

                //Status
                statusDetailsOption: (statusDetail: string) => this.genLoc(`//span[text()='${statusDetail}']/ancestor::li[@class='dropdown-select__select-option cursor-pointer']`),
                statusDetailsInput: this.genLoc("//li[@class='dropdown-select__filter-selected cursor-pointer']"),
                statusDisplay: this.genLoc("//span[contains(@class,'status-rq')]/span[2]"),
                statusDropdownOptions: this.genLoc('//div[@class="selectize-dropdown-content"]//div[@data-selectable]'),

                //Assignee
                inputSearchMember: this.genLoc("//input[@name='assignee_id' and @placeholder='Search...']"),
                optionMember: this.genLoc("//div[contains(@class,'autocomplete-option')]"),
                btnAssignee: this.genLoc("//span[text()='Assignee:']/parent::div[contains(@class,'case-tour-step-two btn-update-case')]"),
                noOptionFound: this.genLoc("//div[@class='no-options']"),
                optionSearchExist: (email: string) => this.genLoc(`//div[@class='autocomplete-option']/div/span[text()='${email}']`),
                dropdownOptions: this.genLoc("//div[@class='autocomplete-dropdown-options']"),
                btnSubmit: this.genLoc("//button[text()='Submit']"),
                fullnameAssignee: this.genLoc("//span[contains(@class,'assignee-full-name')]"),

                //Dive deeper
                firstSuggestBusiness: this.genLoc("//div[@class='recommend-items']/div[position()=1]/p"),
                labelByStepCreateRequest: (step: number) => this.genLoc(`//label[@class='select-step-value select-step-${step} cl-gray']`),
                btnCreateNewRequest: this.genLoc("//a[@data-user-tracking='BTN_SUBMIT_NEW_REQUEST_WITH_BUSINESS']"),
                listBusinesses: this.genLoc("//a[contains(@class,'logo-contact')]"),
                singleBusinesses: (name: string) => this.genLoc(`//a[contains(@class,'logo-contact') and @data-tooltip-content='${name}']`),
                btnDropDownActionBySingleBusiness: (name: string) => this.genLoc(`//a[contains(@class,'logo-contact') and @data-tooltip-content='${name}']`),
                btnDropdownBusiness: this.genLoc("//div[contains(@class,'dropdown action-case-participant')]"),
                btnActivityRequest: this.genLoc("//div[@data-user-tracking='BTN_SHOW_REQUEST_ACTIVITY_MODAL']"),
                btnInDropdownBusiness: (name: string) => this.genLoc(`//span[@data-user-tracking='${name}']`),
                popupSwal: this.genLoc("//div[@class='swal2-popup swal2-modal swal2-show']"),
                btnCofirmArchive: this.genLoc("//button[@class='swal2-confirm swal2-styled']"),
                btnViewArchivedBusiness: this.genLoc("//p[contains(text(),'View archived business')]"),
                listArchiveRequests: this.genLoc("(//h2[text()='Archived Request']/following::table)[1]/tbody/tr"),
                listLinkArchiveRequests: this.genLoc("(//h2[text()='Archived Request']/following::table)[1]/tbody/tr"),
                requestHadStarIt: (requestID: string) => this.genLoc(`//a[@href="/requests/${requestID}"]/*[name()='svg']`),
                keyFocus: (type: string) => this.genLoc(`//p[contains(text(),'${type}')]/ancestor::div[contains(@class,'request-type-items request-type-items-flip')]`),
                btnStarItInModalFocus: (caseID: string) => this.genLoc(`((((//span[@class='cl-gray d-block text-ellipsis cursor-pointer']/*[name()='svg'])/preceding::a[text()='${caseID}'])[2])/ancestor::tr)/descendant::span[@class='cl-gray d-block text-ellipsis cursor-pointer']/*[name()='svg']`),
                headingTableRequest: (headerName: string) => this.genLoc(`//thead/tr/th[normalize-space(span)='${headerName}']`),
                threeDotCustomizeColumnRequest: this.genLoc("//h2[text()='Request Activity']/following::div[@class='dropdown d-flex align-items-center']"),
                listRequestOfBusiness: this.genLoc("//h2[text()='Request Activity']/following::table[1]/tbody/tr"),
                radioCheckAddNew: this.genLoc("//input[@name='action_move_request' and @value='add_new']"),
                inputAddNewDOI: this.genLoc("//div[@class='box-add-new-case']/descendant::input[@id='date_time_date_of_injury']"),
                inputMoveRequest: this.genLoc("(//input[@name='move_to_case_id'])[1]"),

                //Quick summary
                dataRequestType: (type: string) => this.genLoc(`//div[@data-tooltip-content='${type}']`),
                textSummaryDisplay: this.genLoc("//p[contains(@class,'request-type-name')]")
            },

            buttonByText: (name: string) => this.genLoc(`//button[text()='${name}']`),
            mainContainer: this.genLoc(`//div[@id='root']`),
            paginationInfo: this.genLoc(`//div[@id='root']/descendant::div[@class='card-body border-bottom p-3']`),
            bulkEditBtn: this.genLoc(`//button[contains(text(),  'Bulk Edit')]`),
            filterBtn: this.genLoc(`//button[contains(text(),  'Filter')]`),
            caseRow: this.genLoc(`//table[contains(@class, 'table-business-client')]//tbody`),
            heading: this.genLoc(`//div[@id='root']//span[contains(text(), '${this.businessPlural}')]`),
            personalSearch: this.genLoc(`//input[@class='form-control' and @placeholder='Search...']`),
            msgNoResultFound: this.genLoc(`//div[contains(text(), 'No matching results found. Try again.') or contains(text(), 'Create a new case')]`),
            tableHeadingColumn: (name: string) => this.genLoc(`//table//thead//th[contains(normalize-space(), '${name}')]`),
            btnSubmitFocusKey: this.genLoc("//button[@class='btn btn-primary btn-confirm-request-verify']"),

            //From old file case.ts
            pageTitle: this.genLoc(`//div[@id='root']//span[contains(text(), 'Cases')]`),
            btnNewCase: this.genLoc(`//div[@id='root']//button[contains(text(), 'New Case')]`),
            btnBulkEdit: this.genLoc(`//div[@id='root']//button[contains(text(), 'Bulk Edit')]`),
            caseStepOneBox: this.genLoc(`//div[contains(@class, 'box-record')]//p[text()='999033']/preceding-sibling::p//input[@type='checkbox']`),
            btnNextStepOne: this.genLoc(`//button[contains(text(), 'Next')]`),
            btnApplyStepTwo: this.genLoc(`//label[.//span[contains(text(), "Modify tag")]]//input[@name="bulk-action"]`),
            modifyTagStepThree: this.genLoc(`//input[@placeholder="Select or create tags..."]`),
            addtagStepThree: this.genLoc(`//div[@class="dropdown-menu-wrapper"]//li[contains(text(), "Add")]`),
            modifyTagStepFour: this.genLoc(`//td[contains(text(), 'Modify tag')]`),
            addTagStepFour: this.genLoc(`//td[contains(text(), 'Add to existing')]`),
            caseNumberStepFour: this.genLoc(`//a[@href="/cases/999033" and text()="999033"]`),
            btnConfirm: this.genLoc(`//button[contains(text(), 'Confirmation')]`),
            btnFilter: this.genLoc(`//button[contains(@class, 'btn-filter')][2]`), // có 2 xpath 
            modalFilterContainer: this.genLoc(`//div[contains(@class, 'modal-content') and .//h3[contains(normalize-space(),'Filter')]]`),
            iconCloseModalFilter: this.genLoc(`//div[contains(@class, 'modal-content') and .//h3[contains(normalize-space(),'Filter')]]//button[contains(@class, 'btn-close')]`),
            btnThreedot: this.genLoc(`//div[@class='cursor-pointer']`),
            customizedColumnMenu: this.genLoc(`//span[contains(@class, 'dropdown-item') and normalize-space()='Customized Columns']`),
            modalCustomizedColumn: this.genLoc(`//div[contains(@class, 'modal-content') and .//h3[contains(normalize-space(),'Customized Columns')]]`),
            iconCloseModalCustomizedColumn: this.genLoc(`//div[contains(@class, 'modal-content') and .//h3[contains(normalize-space(),'Customized Columns')]]//button[contains(@class, 'btn-close')]`),
            perPageInput: this.genLoc(`//input[@name='per_page']`),
            entriesTotal: this.genLoc(`//div[contains(@class, 'pagination-in-business')]`),
            caseRecords: this.genLoc(`//table[contains(@class, 'table-business-client')]//tbody//tr`),
            inputSearch: this.genLoc(`//div[contains(@class, 'personal-search')]//input[@placeholder='Search...']`),
            // tableHeadingColumn: (name: string) =>
            //     this.genLoc(`//th[contains(@class, 'title-table') and contains(normalize-space(), '${name}')]`).first(),
            pinIcon: (caseNumber: string) =>
                this.genLoc(`//td[normalize-space()='${caseNumber}']/preceding-sibling::td/a[contains(@data-tooltip-content, 'Click here to pin')]`),
            pinnedIcon: (caseNumber: string) =>
                this.genLoc(`//a[normalize-space()='${caseNumber}']/ancestor::tr//a[@data-tooltip-content='Click here to unpin!']`),
            firstCaseNumber: (caseNumber: string) =>
                this.genLoc(`//div[contains(@class, 'pin-card')]//a[contains(@href, "/cases/${caseNumber}")]`),
        }
    }



    get caseSnapshot() {
        return {
            tableSearchUniqueSnapshot: (searchValue: string, clientName: string) => tableSearchUniqueSnapshot(searchValue, clientName),
            caseDetailLackInfo: caseDetailLackInfo,
            caseDetailFullInfo: caseDetailFullInfo,
            headingAndCreateButton: headingAndCreateButton,
            tipsBlock: tipsBlock,
            emptyState: emptyState,
            haveRecord: haveRecord,
            caseUpdateUIHeader: caseUpdateUIHeader,
            caseUpdateUIBody: caseUpdateUIBody,
            caseUpdateUIFooter: caseUpdateUIFooter
        }
    }
    async open() {
        await this.page.goto('cases');
    }
    async getRowCount(): Promise<number> {
        return this.caseLoc.caseRow.count();
    }
    async getPaginationInfoText(): Promise<string> {
        return this.caseLoc.paginationInfo.innerText();
    }
    async bulkBtnStatus(): Promise<boolean> {
        return await this.caseLoc.bulkEditBtn.isDisabled();
    }
    async filterBtnStatus(): Promise<boolean> {
        return await this.caseLoc.filterBtn.isDisabled();
    }
    async search(keyword: string) {
        await this.caseLoc.personalSearch.fill(keyword);
    }
    async clickHeadingNameColumn(name: string) {
        await this.caseLoc.tableHeadingColumn(name).click();
    }
    async getSortedData(columnIndex: number, isAscending: boolean): Promise<string[]> {
        const data = await this.getTableData(columnIndex);
        const sorted = [...data].sort((a, b) => a.localeCompare(b));
        if (isAscending) {
            return sorted
        } else {
            return sorted.reverse();
        }
    }

    async gotoArchive(caseID: string): Promise<void> {
        await this.go(`cases/${caseID}?view_participant_archived=true`)
    }

    async fillDataCreateClient(infoClient: { birthday: string, phone: string, address: string }, email: string): Promise<void> {
        await this.caseLoc.create.detail.inputCreateClientName("birthday").fill(infoClient.birthday);
        await this.caseLoc.create.detail.inputCreateClientName("phone_number").first().fill(infoClient.phone);
        await this.caseLoc.create.detail.inputCreateClientName("email_address").first().fill(email);
        await this.caseLoc.create.detail.inputCreateClientName("address_1").first().fill(infoClient.address);

        await this.caseLoc.create.btnCreate.first().click();
    }

    async fillCaseDetail(detail: { business: string, category: string, description: string }, clientName: string, doi?: string, createNewBusiness?: boolean): Promise<void> {
        await this.caseLoc.create.detail.doi.fill(doi || "");

        if (!createNewBusiness) {
            await this.caseLoc.create.detail.bussiness.type(detail.business);
            await this.caseLoc.create.detail.boxTextBusinessByName(detail.business).click();
            await this.dashboardLoc.modal.headerModalh2("Preview").click();
        }
        await this.caseLoc.create.detail.categoryInput.click();
        await this.waitForSecond(1.5);
        await this.caseLoc.create.detail.noOptionsCategory.waitFor({ state: "hidden" });
        await this.caseLoc.create.detail.categoryInput.clear();
        await this.caseLoc.create.detail.categoryInput.type(detail.category, { delay: 50 });
        await this.caseLoc.create.detail.optionCategory(detail.category).waitFor({ state: "visible" });
        await this.caseLoc.create.detail.optionCategory(detail.category).click();
        await this.caseLoc.create.detail.description.fill(detail.description);

        await this.caseLoc.create.detail.inputByPlaceHolder("Select or type a name").first().click();
        await this.caseLoc.create.detail.inputByPlaceHolder("Select or type a name").first().type(clientName, { delay: 100 });
    }

    async fillLegalContact(business: string, userRecive: string) {
        await this.waitForSecond(2);
        await this.caseLoc.detail.noLegal.click({ force: true });
        await this.caseLoc.detail.addLegalModal.btnAddSuggest(business).click();
        await this.caseLoc.detail.addLegalModal.inputByPlaceholder("Enter the attorney's name.").click();
        await this.caseLoc.detail.addLegalModal.inputByPlaceholder("Enter the attorney's name.").fill(userRecive);
        await this.caseLoc.detail.addLegalModal.counselAdd(userRecive).click();
        await this.caseLoc.detail.addLegalModal.inputByPlaceholder("Enter the case manager's name.").click();
        await this.caseLoc.detail.addLegalModal.inputByPlaceholder("Enter the case manager's name.").fill(userRecive);
        await this.caseLoc.detail.addLegalModal.counselAdd(userRecive).click();
    }

    async getNewestActivity(): Promise<string> {
        await this.waitForSecond(2);
        await this.caseLoc.detail.buttonActivity.waitFor({ state: 'visible' });
        await this.caseLoc.detail.buttonActivity.click({ force: true });
        const textActivity = await this.caseLoc.detail.activity.listActivity.first().innerText();
        await this.caseLoc.detail.activity.buttonClose.click();
        return textActivity.replace(/\s+/g, ' ').trim();
    }

    async changeStarFocus(caseID: string): Promise<void> {
        await this.caseLoc.detail.keyFocus("Medical Bill").scrollIntoViewIfNeeded();
        await this.caseLoc.detail.keyFocus("Medical Bill").hover({ timeout: 3_000 });
        await this.caseLoc.detail.keyFocus("Medical Bill").locator("//div[@class='edit-request open-modal-verify cursor-pointer']").click();
        await this.caseLoc.detail.btnStarItInModalFocus(caseID).click({ force: true });
        await this.dashboardLoc.buttonByText("Confirm").click();
        await this.dashboardLoc.msgSuccess.waitFor({ state: 'visible' });
        await this.dashboardLoc.btnClosePopupNotification.click();
    }

    async clickButtonDropdownSelect(dropdown: string): Promise<void> {
        await this.caseLoc.detail.btnDropdownBusiness.waitFor({ state: 'visible' });
        await this.waitForSecond(2);
        await this.caseLoc.detail.btnDropdownBusiness.click({ force: true });
        await this.caseLoc.detail.btnInDropdownBusiness(dropdown).click();
    }

    async tearDownMoveToOldCase(caseID: string): Promise<void> {
        await this.clickButtonDropdownSelect("BTN_SHOW_MOVE_REQUEST_OF_BUSINESS_MODAL");
        await this.caseLoc.detail.inputMoveRequest.click();
        await this.caseLoc.detail.inputMoveRequest.type(caseID, { delay: 100 });
        await this.caseLoc.detail.transfer.boxOption(caseID).click();
        await this.caseLoc.buttonByText("Move").click();
    }

    // Login as another user in a new browser context and return the new RequestPage
    async loginInAnotherBrowser(browser: Browser, username: string, password: string): Promise<{ context: BrowserContext; page: Page; casePage: CasePage }> {
        const context = await browser.newContext();
        const page = await context.newPage();
        const loginPage = new LoginPage(page);
        await loginPage.open();
        await loginPage.login(username, password);
        await expect(loginPage.baseLoc.dashboardContainer).toBeVisible();
        return { context, page, casePage: new CasePage(page) };
    }

    async addBusinessInDetail(businessName: string): Promise<void> {
        await this.caseLoc.detail.listBusinesses.last().click();
        await this.dashboardLoc.modal.headerModal("Business").waitFor({ state: 'visible' });
        await this.dashboardLoc.modal.inputByID("autocomplete_business_provider_id").type(businessName, { delay: 100 });
        await this.caseLoc.create.detail.boxTextBusinessByName(businessName).waitFor({ state: 'visible' });
        await this.caseLoc.create.detail.boxTextBusinessByName(businessName).click();
        await this.dashboardLoc.buttonByText("Save").first().click();
        await this.dashboardLoc.msgAddBusinessInDetail.waitFor({ state: 'visible' });
        await this.dashboardLoc.btnClosePopupNotification.click();
    }

    async removeBusiness(businessName: string): Promise<void> {
        const businessBtn = this.caseLoc.detail.btnDropDownActionBySingleBusiness(businessName);
        await businessBtn.click();
        await businessBtn.waitFor({ state: 'visible' });
        // Wait for active class to be applied
        await this.page.waitForSelector(`[class*="active"]`);
        await this.caseLoc.detail.btnDropdownBusiness.click();
        await this.caseLoc.detail.dropdownOption("Remove").click();
        await this.dashboardLoc.msgRemoveBussinessSuccess.waitFor({ state: 'visible' });
        await this.dashboardLoc.btnClosePopupNotification.click();
        await businessBtn.waitFor({ state: 'hidden' });
    }

    async createSimpleNewCase(clientName: string, doi: string, dob: string): Promise<void> {
        await this.caseLoc.buttonByText("New Case").click();

        // Fill DOI
        await this.caseLoc.create.inputDOI.fill(doi);

        //Open modal create new client
        await this.caseLoc.create.detail.inputByPlaceHolder("Select or type a name").first().click();
        await this.caseLoc.create.detail.inputByPlaceHolder("Select or type a name").first().type(clientName, { delay: 100 });
        await this.caseLoc.create.detail.createActive.first().click();
        await this.dashboardLoc.modal.headerModal("New Client").waitFor({ state: 'visible' })
        await this.dashboardLoc.modal.inputByID("date_time_birthday").fill(dob);
        await this.dashboardLoc.buttonByText("Create").first().click();
    }

    async createCaseAndRequest(casePage: CasePage, clientName: string, doi: string, dob: string, userReceive: string, businessName: string): Promise<RequestPage> {
        await this.createSimpleNewCase(clientName, doi, dob);
        await this.dashboardLoc.btnClosePopupNotification.click();
        await this.dashboardLoc.buttonByText("Create Case").click();
        await this.caseLoc.detail.createNewRequestWithNewCase.click();

        const requestPage = new RequestPage(casePage.page);
        await requestPage.createSimpleAndShareRequest(userReceive, businessName, clientName);
        return requestPage;
    }

    async loginAndSearchCase(requestPage: RequestPage, browser: any, username: string, password: string, searchTerm: string): Promise<{ casePage: CasePage; caseID: string }> {
        const { requestPage: requestPageB } = await requestPage.loginInAnotherBrowser(
            browser,
            username,
            password
        );
        const casePage = new CasePage(requestPageB.page);
        await casePage.open();
        await casePage.search(searchTerm);
        await casePage.waitForSecond(3);
        const caseID = await casePage.caseLoc.linkcase.newCaseID.innerText();
        return { casePage, caseID };
    }
}