package Requisition;

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Sheet;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.AssertJUnit;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import RevalERP_HRMS.basesetup.BaseSetup;
import RevalERP_HRMS.elements.Requisition_Elements;
import RevalERP_HRMS.excels.Excels;
import RevalERP_HRMS.utils.CommonUtils;

public class Requestion_NewChanges extends BaseSetup {

	public Sheet sheet;
	public Requisition_Elements Elements;
	public WebDriverWait wait;
	public int attempts = 0;
	public int maxAttempts = 3;
	public int i;

	@BeforeClass
	public void setUp() throws Throwable {
		// openbrowser();
		CommonUtils.ModuleName = "Requestion_NewChanges";
		driver = getDriver();
		driver.manage().window().maximize();
		driver.get(baseUrl);
		CommonUtils.Reports("Requestion_NewChanges.html", "Requestion_NewChanges");
		sheet1 = CommonUtils.readExcelSheet(Excels.filepath + "Requisition_TestData.xls", 2);
		Elements = PageFactory.initElements(driver, Requisition_Elements.class);
		CommonUtils.login();
		wait = new WebDriverWait(driver, Duration.ofSeconds(20));
	}

	@Test(priority = 1)
	public void NavigateAddRequisitionPage_Tc_01() throws IOException {
		driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); // while(attempts<maxAttempts) {
	

			try {
				if (Elements.HRMS.isDisplayed()) {
					CommonUtils.scrollTOElement(Elements.HRMS, driver);
					CommonUtils.Thread_Sleep(2);
					CommonUtils.JS_Click(driver, Elements.HRMS);
					CommonUtils.captureScreenshot_pass(driver, "TC_001",
							"Home page Hrms Main modules is visable and clickable also");
				}
			} catch (Exception E) {
				CommonUtils.captureScreenshot_fail(driver, "TC_001",
						"Home page Hrms Main modules is  not visable and unable clickable also");

			}
			CommonUtils.Thread_Sleep(2);
			try {
				if (Elements.Requisition.isDisplayed()) {
					CommonUtils.scroll_down(driver);
					CommonUtils.JS_Click(driver, Elements.Requisition);
					CommonUtils.captureScreenshot_pass(driver, "TC_002",
							"Inside the  HRMS -Requisition section is displayed and click able alos");
				}
			} catch (Exception E) {
				CommonUtils.captureScreenshot_fail(driver, "TC_002",
						"Inside the  HRMS -Requisition section is  not displayed and unable to click able alos");

			}
			CommonUtils.Thread_Sleep(3);
			wait.until(ExpectedConditions.visibilityOf(Elements.Requisition_Module));
			CommonUtils.JS_Click(driver, Elements.Requisition_Module);
			CommonUtils.Thread_Sleep(3);
		
	}
	@Test(priority = 2)
	public void PhaseTwo_ListpageNewChanges() throws Exception {
		try {
			if(Elements.Search_HelpText.isDisplayed()) {
				String SearchwordHelpText=Elements.Search_HelpText.getText();
				System.out.println("Search word Help text:-"+SearchwordHelpText);
				if(SearchwordHelpText==CommonUtils.getExcelData(8, 2, sheet1));
				CommonUtils.captureScreenshot_pass(driver, "TC_001", "TC_001 Search word field Updated Help text should displayed correctly");
			}
		}catch(Exception E) {
			CommonUtils.captureScreenshot_fail(driver, "TC_001", "TC_001 Search word field Updated Help text shouldn't displayed correctly");

		}
		if(Elements.JobTitle_JobCode_Gride.isDisplayed()) {
		String ListpageRecord = Elements.Listpage_JobTitle_JobCode.getText();
		System.out.println("JobTitle/JobCode" + ListpageRecord);

		// Split by line breaks and take the first line only
		String firstLine = ListpageRecord.split("\\r?\\n")[0];
		String LastLine = ListpageRecord.split("\\r?\\n")[1];
System.out.println(LastLine);
		// Print the first line
		System.out.println("First line: " + firstLine);

		try {
			if (Elements.search.isDisplayed()) {
				Elements.search.click();
				Elements.search.sendKeys(firstLine);
	
				if (Elements.Submit.isDisplayed())
					CommonUtils.Thread_Sleep(2);
				CommonUtils.JS_Click(Elements.Submit);
				if (Elements.Listpage_JobTitle_JobCode.isDisplayed()) {
					CommonUtils.captureScreenshot_pass(driver, "TC_1.1",
							"TC_1.1 Schedule Interview page Job title and Job code displayed on single coloum & search field functionality also working fine");

				}
			}
		} catch (Exception E) {
			CommonUtils.captureScreenshot_fail(driver, "TC_1.1",
					"TC_1.1 Consultancy Assessment page Job title and Job code displayed on single coloum & search field functionality not  working fine");

		}
	

	try {
		if (Elements.search.isDisplayed()) {
			Elements.search.click();
			Elements.search.clear();
			Elements.search.sendKeys(LastLine);

			if (Elements.Submit.isDisplayed())
				CommonUtils.Thread_Sleep(2);
			CommonUtils.JS_Click(Elements.Submit);
			if (Elements.Listpage_JobTitle_JobCode.isDisplayed()) {
				CommonUtils.captureScreenshot_pass(driver, "TC_1.2",
						"TC_1.2 Consultancy Assessment page Job title and Job code displayed on single coloum & search field functionality also working fine");

			}
		}
	} catch (Exception E) {
		CommonUtils.captureScreenshot_fail(driver, "TC_1.2",
				"TC_1.2 Schedule Interview  page Job title and Job code displayed on single coloum & search field functionality not  working fine");

	}
	driver.navigate().refresh();
	CommonUtils.Thread_Sleep(3);
	}
try {
	if(Elements.Status_Gride.isDisplayed()) {
		CommonUtils.captureScreenshot_pass(driver, "TC_03", "Verify \"Current Status\" column renamed to \"Status\" on HM List Page grid");
	}
}catch(Exception E){
	CommonUtils.captureScreenshot_fail(driver, "TC_03", "Verify \"Current Status\" unable to  column renamed to \"Status\" on HM List Page grid");

}
try {
    if (Elements.ListPage_RequiestionData.isDisplayed()) {
        String requistionDate = Elements.ListPage_RequiestionData.getText();
        if (requistionDate != null) {
            CommonUtils.captureScreenshot_fail(driver, "TC_002", "Requisition date is binding on the requisition list page.");
        }
    }
} catch (Exception e) {
    CommonUtils.captureScreenshot_fail(driver, "TC_002", "Requisition date is not binding on the requisition list page.");
}
try {
    if (!Elements.ListPage_DepartmentDropdown.isDisplayed()) {
        CommonUtils.captureScreenshot_pass(driver, "TC_04", "List page Department dropdown is removed as per the new requirement (Phase 2).");
    }
} catch (Exception e) {
    CommonUtils.captureScreenshot_fail(driver, "TC_04", "List page Department dropdown could not be removed as per the new requirement (Phase 2).");
}
try {
	if(Elements.RequiestionData_Gride.isDisplayed()) {
		CommonUtils.captureScreenshot_pass(driver, "TC_07", "Verify \"Submission Date\" column is renamed to \"Requisition Date\" on HR List Page grid");
	}
}catch(Exception E) {
	CommonUtils.captureScreenshot_pass(driver, "TC_07", "Verify \"Submission Date\" column is unable to renamed to \"Requisition Date\" on HR List Page grid");

}
}
	@Test(priority = 3)
	public void AddPage() throws Exception {
		CommonUtils.Thread_Sleep(3);
		try {
		    if (Elements.Listpage_JobTitle_JobCode.isDisplayed()) {
		        CommonUtils.JS_Click(Elements.Listpage_JobTitle_JobCode);
		        CommonUtils.Thread_Sleep(2);

		        if (Elements.JobCode_Textfield_DisableMode.isDisplayed() && Elements.StatusField_DisableMode.isDisplayed()) {
		            String jobCode = Elements.JobCode_Textfield_DisableMode.getText();
		            String status = Elements.StatusField_DisableMode.getText();

		            // Check for the 'Disable' label above the fields
		            if (Elements.JobCode_Textfield_DisableMode.isDisplayed()) {
		                String disableLabelText = Elements.JobCode_Textfield_DisableMode.getText();

		                if ((jobCode != null && !jobCode.isEmpty()) || (status != null && !status.isEmpty())) {
		                    if (disableLabelText.equalsIgnoreCase("Disable")) {
		                        CommonUtils.captureScreenshot_pass(driver, "TC_08", "Verified: 'Job Code' and 'Status' fields are displayed as non-editable (read-only) with 'Disable' label on HM Edit Page.");
		                    } else {
		                        CommonUtils.captureScreenshot_fail(driver, "TC_08", "Fields are non-editable but 'Disable' label is missing or incorrect.");
		                    }
		                } else {
		                    CommonUtils.captureScreenshot_fail(driver, "TC_08", "Job Code or Status values are missing.");
		                }
		            } else {
		                CommonUtils.captureScreenshot_fail(driver, "TC_08", "'Disable' label above Job Code and Status fields is not displayed.");
		            }
		        } else {
		            CommonUtils.captureScreenshot_fail(driver, "TC_08", "Job Code and/or Status fields are not in non-editable (disabled) mode.");
		        }
		    } else {
		        CommonUtils.captureScreenshot_fail(driver, "TC_08", "Add Requisition button is not displayed.");
		    }
		} catch (Exception e) {
		    CommonUtils.captureScreenshot_fail(driver, "TC_08", "Functionality failed: Could not verify that 'Job Code' and 'Status' fields are non-editable with 'Disable' label on HM Edit Page.");
		}

	}
	@Test(priority = 4)
	public void Max_MinCTC_TextField() throws Exception {
		CommonUtils.scrollTOElement(Elements.MaxCTC_Textfield, driver);
		CommonUtils.Thread_Sleep(2);
		try {
			if(Elements.MinCTC_Textfield.isDisplayed()&&Elements.MaxCTC_Textfield.isDisplayed()&Elements.Expected_DOJ.isDisplayed()) {
				CommonUtils.captureScreenshot_pass(driver, "TC_10,TC_19", "Modify Requestion page Max and MIN propoused CTC text field & Expected DOJ  is add ");
			}
		}catch(Exception E) {
			CommonUtils.captureScreenshot_fail(driver, "TC_10,19", "Modify Requestion page Max and MIN propoused CTC text & Expected DOJ field is  not add ");

		}
		for (int i = 1; i <= 5; i++) {

		    CommonUtils.Thread_Sleep(2); // Wait for any async load to settle

		    String testCaseID = "TC_11." + i;
		    
		    try {
		        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
		        wait.until(ExpectedConditions.visibilityOf(Elements.MinCTC_Textfield));

		        // Click using JS in case normal click fails
		        CommonUtils.JS_Click(Elements.MinCTC_Textfield);

		        Elements.MinCTC_Textfield.clear();

		        String inputValue = CommonUtils.getExcelData(i, 9, sheet1);
		        Elements.MinCTC_Textfield.sendKeys(inputValue);

		        System.out.println("MinCTC Input Set: " + inputValue);

		    } catch (Exception e) {
		        System.out.println(testCaseID + " - MinCTC_TextField not displaying or not accepting input.");
		        CommonUtils.captureScreenshot_fail(driver, testCaseID, "MinCTC_TextField not ready or input failed.");
		        continue; // Skip validation check if input fails
		    }

		    // Validation check
		    try {
		        String expectedValidationText = CommonUtils.getExcelData(i, 10, sheet1);
		        WebElement validationMessage = new WebDriverWait(driver, Duration.ofSeconds(5)).until(
		            ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[text()='" + expectedValidationText + "']"))
		        );

		        if (validationMessage.isDisplayed()) {
		            CommonUtils.captureScreenshot_pass(driver, testCaseID, "Min Proposed CTC validation passed for " + testCaseID);
		            System.out.println("Pass: " + testCaseID);
		        }

		    } catch (Exception e) {
		        CommonUtils.captureScreenshot_fail(driver, testCaseID, "Min Proposed CTC validation failed for " + testCaseID);
		        System.out.println("Fail: " + testCaseID);
		    }
		}

		for (int i = 1; i <= 5; i++) {

			//driver.navigate().refresh();
			CommonUtils.Thread_Sleep(2);
			String testCaseID = "TC_" + ("11" + i);
			try {
				AssertJUnit.assertTrue(Elements.MaxCTC_Textfield.isDisplayed());
				Elements.MaxCTC_Textfield.click();
				Elements.MaxCTC_Textfield.clear();
				Elements.MaxCTC_Textfield.sendKeys(CommonUtils.getExcelData(i, 11, sheet1));
			} catch (Exception e) {
				System.out.println("MinCTC_Text Field not Displaying");
			}
			try {
				if (driver.findElement(By.xpath("//*[text()='" + CommonUtils.getExcelData(i, 12, sheet1) + "']"))
						.isDisplayed()) {
					CommonUtils.captureScreenshot_pass(driver, "TC_11To TC_17." + testCaseID, "Max Proposed CTC Validation is Working"+testCaseID);
					System.out.println("Pass");
				}
			} catch (Exception e) {
				CommonUtils.captureScreenshot_fail(driver, "TC_11 To TC_17."+testCaseID, "Max Proposed CTC Validation is not Working"+testCaseID);
				System.out.println("fail");
			}
		}
	}
}