const { strict: assert } = require('assert');
const {
  TEST_SEED_PHRASE,
  withFixtures,
  completeImportSRPOnboardingFlow,
  sendTransaction,
  findAnotherAccountFromAccountList,
  locateAccountBalanceDOM,
  logInWithBalanceValidation,
  regularDelayMs,
  unlockWallet,
  WALLET_PASSWORD,
  generateGanacheOptions,
} = require('../../helpers');

const FixtureBuilder = require('../../fixture-builder');

describe('Add account', function () {
  const secondAccount = '0x3ED0eE22E0685Ebbf07b2360A8331693c413CC59';

  const ganacheOptions = generateGanacheOptions({
    secretKey:
      '0x53CB0AB5226EEBF4D872113D98332C1555DC304443BEE1CF759D15798D3C55A9',
  });

  it('should display correct new account name after create', async function () {
    await withFixtures(
      {
        fixtures: new FixtureBuilder().build(),
        ganacheOptions,
        title: this.test.fullTitle(),
      },
      async ({ driver }) => {
        await unlockWallet(driver);

        await driver.clickElement('[data-testid="account-menu-icon"]');
        await driver.clickElement(
          '[data-testid="multichain-account-menu-popover-action-button"]',
        );
        await driver.clickElement(
          '[data-testid="multichain-account-menu-popover-add-account"]',
        );

        await driver.fill('[placeholder="Account 2"]', '2nd account');
        // needed to mitigate a race condition with the state update
        // there is no condition we can wait for in the UI
        await driver.delay(regularDelayMs);
        await driver.clickElement({ text: 'Add account', tag: 'button' });
        await driver.findElement({
          css: '[data-testid="account-menu-icon"]',
          text: '2nd account',
        });
      },
    );
  });

  it('should not affect public address when using secret recovery phrase to recover account with non-zero balance @no-mmi', async function () {
    await withFixtures(
      {
        fixtures: new FixtureBuilder({ onboarding: true }).build(),
        ganacheOptions,
        title: this.test.fullTitle(),
      },
      async ({ driver, ganacheServer }) => {
        await driver.navigate();

        // On boarding with 1st account
        await completeImportSRPOnboardingFlow(
          driver,
          TEST_SEED_PHRASE,
          WALLET_PASSWORD,
        );

        // Check address of 1st accoun
        await locateAccountBalanceDOM(driver, ganacheServer);
        await driver.findElement('[data-testid="app-header-copy-button"]');

        // Create 2nd account
        await driver.clickElement('[data-testid="account-menu-icon"]');
        // Wait until account list is loaded to mitigate race condition
        await driver.waitForSelector({
          text: 'Account 1',
          tag: 'span',
        });
        await driver.clickElement(
          '[data-testid="multichain-account-menu-popover-action-button"]',
        );
        await driver.clickElement(
          '[data-testid="multichain-account-menu-popover-add-account"]',
        );
        await driver.fill('[placeholder="Account 2"]', '2nd account');
        // needed to mitigate a race condition with the state update
        // there is no condition we can wait for in the UI
        await driver.delay(regularDelayMs);
        await driver.clickElement({ text: 'Add account', tag: 'button' });

        // Check address of 2nd account
        await locateAccountBalanceDOM(driver);
        await driver.findElement('[data-testid="app-header-copy-button"]');

        // Log into the account with balance(account 1)
        // and transfer some balance to 2nd account
        // so they will not be removed after recovering SRP
        const accountOneSelector = await findAnotherAccountFromAccountList(
          driver,
          1,
          'Account 1',
        );
        await locateAccountBalanceDOM(driver);
        await driver.clickElement(accountOneSelector);
        await sendTransaction(driver, secondAccount, '2.8');

        // Lock the account
        await driver.clickElement(
          '[data-testid="account-options-menu-button"]',
        );

        await driver.clickElement('[data-testid="global-menu-lock"]');
        await driver.waitForSelector('[data-testid="unlock-page"]');

        // Recover via SRP in "forget password" option
        await driver.clickElement('.unlock-page__link');
        await driver.pasteIntoField(
          '[data-testid="import-srp__srp-word-0"]',
          TEST_SEED_PHRASE,
        );
        await driver.fill('#password', 'correct horse battery staple');
        await driver.fill('#confirm-password', 'correct horse battery staple');

        await driver.clickElement(
          '[data-testid="create-new-vault-submit-button"]',
        );

        // Land in 1st account home page
        await driver.findElement('.home__main-view');
        await locateAccountBalanceDOM(driver);

        // Check address of 1st account
        await driver.findElement('[data-testid="app-header-copy-button"]');

        // Check address of 2nd account
        await driver.clickElement('[data-testid="account-menu-icon"]');
        await driver.clickElement({
          css: `.multichain-account-list-item__account-name__button`,
          text: 'Account 2',
        });

        await driver.findElement('[data-testid="app-header-copy-button"]');
      },
    );
  });

  it('should be possible to remove an account imported with a private key, but should not be possible to remove an account generated from the SRP imported in onboarding @no-mmi', async function () {
    const testPrivateKey =
      '14abe6f4aab7f9f626fe981c864d0adeb5685f289ac9270c27b8fd790b4235d6';

    await withFixtures(
      {
        fixtures: new FixtureBuilder().build(),
        ganacheOptions,
        title: this.test.fullTitle(),
      },
      async ({ driver }) => {
        await logInWithBalanceValidation(driver);

        await driver.clickElement('[data-testid="account-menu-icon"]');
        await driver.clickElement(
          '[data-testid="multichain-account-menu-popover-action-button"]',
        );
        await driver.clickElement(
          '[data-testid="multichain-account-menu-popover-add-account"]',
        );
        await driver.fill('[placeholder="Account 2"]', '2nd account');
        // needed to mitigate a race condition with the state update
        // there is no condition we can wait for in the UI
        await driver.delay(regularDelayMs);
        await driver.clickElement({ text: 'Add account', tag: 'button' });

        // Wait for 2nd account to be created
        await locateAccountBalanceDOM(driver);
        await driver.findElement({
          css: '[data-testid="account-menu-icon"]',
          text: '2nd account',
        });

        await driver.clickElement('[data-testid="account-menu-icon"]');
        const menuItems = await driver.findElements(
          '.multichain-account-list-item',
        );
        assert.equal(menuItems.length, 2);

        // User cannot delete 2nd account generated from the SRP imported in onboarding
        await driver.clickElement(
          '.multichain-account-list-item--selected [data-testid="account-list-item-menu-button"]',
        );
        await driver.assertElementNotPresent(
          '[data-testid="account-list-menu-remove"]',
        );

        // Create 3rd account with private key
        await driver.clickElement('.mm-text-field');
        await driver.clickElement(
          '[data-testid="multichain-account-menu-popover-action-button"]',
        );
        await driver.clickElement({ text: 'Import account', tag: 'button' });
        await driver.fill('#private-key-box', testPrivateKey);

        await driver.clickElement(
          '[data-testid="import-account-confirm-button"]',
        );

        // Wait for 3rd account to be created
        await locateAccountBalanceDOM(driver);
        await driver.findElement({
          css: '[data-testid="account-menu-icon"]',
          text: 'Account 3',
        });

        // User can delete 3rd account imported with a private key
        await driver.clickElement('[data-testid="account-menu-icon"]');
        const importedMenuItems = await driver.findElements(
          '.multichain-account-list-item',
        );
        assert.equal(importedMenuItems.length, 3);
        await driver.clickElement(
          '.multichain-account-list-item--selected [data-testid="account-list-item-menu-button"]',
        );
        await driver.findElement('[data-testid="account-list-menu-remove"]');
      },
    );
  });
});
