using ESuite.UI.E2E.Helpers;
using OpenQA.Selenium;

namespace ESuite.UI.E2E.Pages
{
    public class LoginPage
    {
        private readonly IWebDriver driver;

        // Constructor to initialize the driver
        public LoginPage(IWebDriver driver)
        {
            this.driver = driver;
        }

        // Page elements
        public By EmailInput => By.Id("Email");
        public By NextButton => By.XPath("//button[text()='Next']");
        public By PasswordInput => By.Id("Password");
        public static By SecurityCodeInput => By.Id("SecurityCode");
        public By LoginButton => By.XPath("//button[text()='Login']");
        public By ForgottenPasswordButton => By.Id("forgot-password");
        public By ForgottenPasswordMessageAlert => By.XPath("//div[@class='alert alert-info emailSent']");
        public By ConfirmPasswordInput => By.CssSelector("#confirmPasswordDiv .password");
        public By ConfirmEmailButton => By.CssSelector("button[name='confirmEmail']");
        public By SaveButton => By.XPath("//button[@type='submit'][text()='Save']");
        public By ActivateButton => By.XPath("//button[@type='submit'][text()='Activate']");
        public By FormMessage(string text) => By.XPath($"//div[text()='{text}']");

        // Page actions
        public void EnterUserEmail(string username)
        {
            I.FillField(EmailInput, username);
        }

        public void EnterPassword(string password)
        {
            I.FillField(PasswordInput, password);
        }

        public static void Enter2FACode(ScenarioContext scenarioContext)
        {
            string? code = null;

            RetryHelper.Retry(() =>
            {
                code = AuthenticationHelper.GenerateOTP(scenarioContext["SecretKey"].ToString()!, scenarioContext);
                if (string.IsNullOrEmpty(code))
                {
                    throw new Exception("Generated OTP code is null or empty. Retrying...");
                }
            }, 3, 1000); 

            if (!string.IsNullOrEmpty(code))
            {
                I.FillField(SecurityCodeInput, code);
            }
        }
    }
}
