import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import { Provider } from 'react-redux';
import history from '../../../utils/history';
import userEvent from '@testing-library/user-event';
import { server } from './msw-handler';
import {
  render,
  fireEvent,
  screen,
  within,
  waitFor,
} from '../../../utils/test-utils';

import { configureStore }  from '@capillarytech/vulcan-react-sdk/utils';
import { initialReducer } from '../../../initialReducer';
import { mockInitialState } from './mocks/initialState';
import TemplatesV2 from '../../../v2Containers/TemplatesV2';
import globalMessages from '../../../v2Containers/Cap/messages';
import rcsMessages from '../../../v2Containers/Rcs/messages';
import * as helper from './helper';

jest.mock('@capillarytech/cap-ui-utils', () => ({
  ...jest.requireActual('@capillarytech/cap-ui-utils'),
  GA: {
    ...jest.requireActual('@capillarytech/cap-ui-utils').GA,
    initialize: jest.fn(),
    setCustomDimension: jest.fn(),
    getCallerName: jest.fn(),
    tracker: {
      trackException: jest.fn(),
    },
  },
}));

jest.setTimeout(60000);

const initializeCreatives = () => { 
  const store = configureStore(mockInitialState, initialReducer, history);
  history.push('creatives/ui/v2');
  render(
    <Provider store={store}>
      <Router history={history}>
        <TemplatesV2 authData={{'user': {'accessiblePermissions': ['CREATIVES_UI_VIEW']}}}/>
      </Router>
    </Provider>,
  );
};

// establish API mocking before all tests
beforeEach(() => {
  server.listen();
  localStorage.clear();
  localStorage.setItem('token', true);
  
  // Mock cap auth
  window.capAuth = {
    hasFeatureAccess: jest.fn().mockReturnValue(false),
    isInitialized: jest.fn().mockReturnValue(true),
  };
});

// clean up once the tests are done
afterAll(() => {
  server.resetHandlers();
  server.close();
  jest.resetAllMocks();
  delete window?.capAuth;
});

describe("Creatives testing template creation", () => {
  it("Should navigate from creatives home page and create template in RCS channel", async () => {
    initializeCreatives();
    const creativesScreen = await helper.getCreativesScreen();
    expect(creativesScreen.getByText(globalMessages.creatives.defaultMessage, {})).toBeInTheDocument();

    // for navigation among different channels
    const rcs = creativesScreen.getByRole('tab', {
      name: /rcs/i,
    });
    const whatsapp = creativesScreen.getByRole('tab', {
      name: /whatsapp/i,
    });

    //Currently weChat tab has been disabled as we dont suppport it anymore
    // const wechat = creativesScreen.getByRole('tab', {
    //   name: /wechat/i,
    // });
    const facebook = creativesScreen.getByRole('tab', {
      name: /facebook/i,
    });
    const mpush = creativesScreen.getByRole('tab', {
      name: /push notification/i,
    });
    const line = creativesScreen.getByRole('tab', {
      name: /line/i,
    });
    const email = creativesScreen.getByRole('tab', {
      name: globalMessages.email.defaultMessage,
    });
    await userEvent.click(whatsapp);
    await waitFor(() => {
      expect(
        creativesScreen.getByText(
          /Whatsapp accounts are not setup for your brand/i
        )
      ).toBeInTheDocument();
    }, { timeout: 5000, interval: 100 });
    await userEvent.click(line);
    //assertions for template filters for line channel
    expect(creativesScreen.getByText(/rich video message/i)).toBeInTheDocument();
    userEvent.click(creativesScreen.getByText(/rich video message/i));
    expect(creativesScreen.getByText(/card message/i)).toBeInTheDocument();
    userEvent.click(creativesScreen.getByText(/card message/i));
    expect(creativesScreen.getByText(/Rich message/i)).toBeInTheDocument();
    userEvent.click(creativesScreen.getByText(/Rich message/i));
    expect(creativesScreen.getByText(/image/i)).toBeInTheDocument();
    userEvent.click(creativesScreen.getByText(/image/i));
    expect(creativesScreen.getByText(/text/i)).toBeInTheDocument();
    userEvent.click(creativesScreen.getByText(/text/i));

     //Currently weChat tab has been disabled as we dont suppport it anymore
    // await userEvent.click(wechat);
    // expect(creativesScreen.getByText(/wechat account/i)).toBeInTheDocument();
    // fireEvent.click(mpush);
    // screen.debug(null, Infinity);
    // await waitFor(() => {
    //   expect(
    //     screen.findByText(/Push notifications are not setup for your brand/i, undefined, { timeout: 10000 })
    //   ).toBeInTheDocument();
    // }, { timeout: 50000, interval: 500 });
    fireEvent.click(email);

    //start of rcs template creation
    fireEvent.click(rcs);
    const createButton = await creativesScreen.findByRole('button', {
      name: /create new/i,
    });
    await waitFor(() => expect(createButton).toBeEnabled(),{timeout: 5000, interval: 100});
    userEvent.click(createButton);
    // expect(await creativesScreen.findByText(/Creative name/i, undefined, {timeout: 10000})).toBeInTheDocument();
    const templateNameInput = await creativesScreen.findByTestId(
      /template_name/,
      {},
    );

    // Enter a template name
    fireEvent.change(templateNameInput, {
      target: { value: 'rcs_test_template' },
    });
    const richCardOption = await creativesScreen.findByText(/rich card/i);
    fireEvent.click(richCardOption);
    const imageRadioBtn = await creativesScreen.findByRole('radio', {
      name: /image/i,
    });
    fireEvent.click(imageRadioBtn);
    const imageUploader = await creativesScreen.findByText(
      /drag and drop image here/i,
    );
    expect(imageUploader).toBeInTheDocument();

    // Enter the template title
    const templateTitleInput = await creativesScreen.findByTestId(
      /template_title/,
      {},
    );
    fireEvent.change(templateTitleInput, {
      target: { value: 'rcs_template_title' },
    });

    // Enter the text in template text area
    const templateTextInput = await creativesScreen.findByTestId(
      /rcs_text_area/,
      {},
    );
    fireEvent.change(templateTextInput, {
      target: { value: 'rcs_template_text' },
    });

    // click on Done button
    const doneButton = creativesScreen.getByRole('button', {
      name: rcsMessages.sendForApprovalButtonLabel.defaultMessage,
    });
    await userEvent.click(doneButton);
    expect(createButton).toBeInTheDocument();
  });

  it("Should navigate from creatives home page and create template in RCS channel with CTA buttons", async () => {
    initializeCreatives();
    const creativesScreen = await helper.getCreativesScreen();
    const rcs = creativesScreen.getByRole('tab', {
      name: /rcs/i,
    });
    await userEvent.click(rcs);
    const createButton = await creativesScreen.findByRole('button', {
      name: /create new/i,
    });
    await waitFor(() => expect(createButton).toBeEnabled(),{ timeout: 5000, interval: 100 });
    await userEvent.click(createButton);
    const richCardOption = await creativesScreen.findByText(/rich card/i);
    fireEvent.click(richCardOption);
    const templateNameInput = await creativesScreen.findByTestId(
      /template_name/,
      {},
    );
    //Enter a template name
    fireEvent.change(templateNameInput, {
      target: { value: 'rcs_test_template' },
    });
    const templateTitleInput = await creativesScreen.findByTestId(
      /template_title/,
      {},
    );
    //Enter a template title
    fireEvent.change(templateTitleInput, {
      target: { value: 'rcs_template_title' },
    });
    const templateTextInput = await creativesScreen.findByTestId(
      /rcs_text_area/,
      {},
    );
    //Enter a template text area
    fireEvent.change(templateTextInput, {
      target: { value: 'rcs_template_text' },
    });
    const addButton = creativesScreen.getByRole('button', {
      name: /add button/i,
    });
    fireEvent.click(addButton);
    const ctaBtnText = creativesScreen.getByPlaceholderText(/enter button text/i);
    fireEvent.change(ctaBtnText, {
      target: { value: 'cta_button' },
    });
    expect(createButton).toBeInTheDocument();
  });

  it("Should navigate from creatives home page and create template in Viber channel", async () => {
    initializeCreatives();
    const creativesScreen = await helper.getCreativesScreen();
    expect(creativesScreen.getByText(/Creatives/i, {})).toBeInTheDocument();
    const viberTab = creativesScreen.getByRole('tab', {
      name: /viber/i,
    });

    // navigating to Viber channel
    await userEvent.click(viberTab);
    const createButton = creativesScreen.getByRole('button', {
      name: /Create new/i,
    });
    await waitFor(() => expect(createButton).toBeEnabled(),{ timeout: 5000, interval: 100 });
    userEvent.click(createButton);
    await userEvent.click(createButton);
    screen.debug(null,Infinity);
    const doneButton = creativesScreen.getByRole('button', {
      name: globalMessages.done.defaultMessage,
    });
    //should be disabled as template is not yet confiured
    expect(doneButton).toBeDisabled(); 

    // enter template name
    const templateNameInput = await creativesScreen.findByTestId(
      /template_name/,
      {},
    );
    fireEvent.change(templateNameInput, {
      target: { value: 'viber_test_template' },
    });
    fireEvent.change(templateNameInput, {
      target: { value: '' },
    });
    // error case assertion
    expect(creativesScreen.getByText(/Template title can not be empty/i)).toBeInTheDocument();
    fireEvent.change(templateNameInput, {
      target: { value: 'viber_test_template' },
    });
    const msgBox = screen.getByPlaceholderText(/Enter message/i);
    msgBox.focus();
    //Enter a template text message
    fireEvent.change(msgBox, {
      target: { value: 'viber_template_message' },
    });

    //assertions for error cases in template message
    fireEvent.change(msgBox, {
      target: { value: '  ' },
    });
    expect(creativesScreen.getByText(/template message cannot be empty/i)).toBeInTheDocument();
    fireEvent.change(msgBox, {
      target: { value: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' },
    });
    expect(creativesScreen.getByText(/Template message length cannot exceed 1000/i)).toBeInTheDocument();
    fireEvent.change(msgBox, {
      target: { value: ' viber_test_template}}} ' },
    });
    expect(creativesScreen.getByText(/Invalid label, please close all curly braces/i)).toBeInTheDocument();
    fireEvent.change(msgBox, {
      target: { value: 'viber_test_template' },
    });
    const addLabel = creativesScreen.getByRole('button', {
      name: globalMessages.addLabels.defaultMessage,
    });
    // first click opens the popup, and second click closes it, clicking twice is intentional
    userEvent.click(addLabel);
    userEvent.click(addLabel);
    const imageRadio = creativesScreen.getByRole('radio', {name: /image/i});
    fireEvent.click(imageRadio);
    const imageUploader = creativesScreen.getByRole('button', {
      name: /drag and drop image here or select from computer gallery/i,
    });
    expect(within(imageUploader).getByRole('button', {
      name: /select from computer/i,
    })).toBeInTheDocument();
    const galleryBtn = within(imageUploader).getByRole('button', {
      name: globalMessages.gallery.defaultMessage,
    });

    //configuring CTA button
    const ctaRadioBtn = creativesScreen.getByRole('radio', {
      name: /call to action create a button that lets customers respond to your messages or take action/i,
    });
    fireEvent.click(ctaRadioBtn);
    const btnTextBox = await creativesScreen.findByPlaceholderText(
      'Enter button text',
    );
    fireEvent.change(btnTextBox, {
      target: { value: 'button' },
    });
    const btnUrlBox = await creativesScreen.findByPlaceholderText(
      'Enter button url',
    );
    fireEvent.change(btnUrlBox, {
      target: { value: 'button' },
    });
    expect(
      creativesScreen.getByText(/button url is not valid/i)
    ).toBeInTheDocument();
    fireEvent.change(btnUrlBox, {
      target: { value: 'https://capillarytech.com/' },
    });
    await userEvent.click(galleryBtn);
    jest.advanceTimersByTime(10000);
    expect(
      screen.getByRole('button', {
        name: /close/i,
      })
    ).toBeInTheDocument();
    await userEvent.click(doneButton);
    expect(createButton).toBeInTheDocument();
  });

  it("Should navigate from creatives home page and create template in Line channel", async () => {
    initializeCreatives();
    const creativesScreen = await helper.getCreativesScreen();
    expect(creativesScreen.getByText(/Creatives/i, {})).toBeInTheDocument();
    const LineTab = creativesScreen.getByRole('tab', {
      name: /Line/i,
    });

    // navigating to Viber channel
    await userEvent.click(LineTab);
    const createButton = await creativesScreen.findByRole('button', {
      name: /create new/i,
    });
  
    await waitFor(() => expect(createButton).toBeEnabled(),{ timeout: 5000, interval: 100 });
    fireEvent.click(createButton);
    const doneButton = creativesScreen.getByRole('button', {
      name: globalMessages.done.defaultMessage,
    });
    //should be disabled as template is not yet confiured
    expect(doneButton).toBeDisabled();
    // enter template name
    const templateNameInput = creativesScreen.getByTestId(
      /template_name/, {});
    fireEvent.change(templateNameInput, {
      target: { value: 'line_test_template' },
    });
    fireEvent.change(templateNameInput, {
      target: { value: '' },
    });
    // error case assertion
    expect(creativesScreen.getByText(/Template title can not be empty/i)).toBeInTheDocument();
    fireEvent.change(templateNameInput, {
      target: { value: 'line_test_template' },
    });

    const templateTextInput = await creativesScreen.getByText(
      /Text message/,
      {},

    );
    const msgBox = templateTextInput.parentElement.nextSibling.firstChild;
    //Enter a template text message
    fireEvent.change(msgBox, {
      target: { value: 'viber_template_message' },
    });

    //assertions for error cases in template message
    fireEvent.change(msgBox, {
      target: { value: '  ' },
    });
    expect(creativesScreen.getByText(/template content can not be empty/i)).toBeInTheDocument();
    fireEvent.change(msgBox, {
      target: { value: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' },
    });
    expect(creativesScreen.getByText(/Template content can not be more than 1600/i)).toBeInTheDocument();
    fireEvent.change(msgBox, {
      target: { value: ' viber_test_template}}} ' },
    });
    expect(creativesScreen.getByText(/Invalid label, please close all curly braces/i)).toBeInTheDocument();
    fireEvent.change(msgBox, {
      target: { value: 'viber_test_template' },
    });
    const addLabel = creativesScreen.getByRole('button', {
      name: globalMessages.addLabels.defaultMessage,
    });
    userEvent.click(addLabel);
    userEvent.click(addLabel);
    //saving the template
    await userEvent.click(doneButton);
    expect(createButton).toBeInTheDocument();
  });
});
