import { config, mount } from '@vue/test-utils';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { defineComponent, inject, nextTick } from 'vue';
import { BmsNotificationsInstance, notifications } from './index';

const MyComponent = defineComponent({
  template: `
  <bms-notifications></bms-notifications>`,
  setup() {
    const notify = inject(BmsNotificationsInstance);

    const notifySuccess = (time, details = '') => {
      notify.success('This is a success', details, time);
    };
    const notifyError = (time, details = '') => {
      notify.error('This is an error', details, time);
    };
    return { notifySuccess, notifyError };
  },
});

const intersectionObserverMock = () => ({
  observe: () => null,
});

const factory = () => mount(MyComponent, { global: { stubs: ['teleport'] } });

config.global.plugins = [notifications];

describe('Notifications', () => {
  beforeEach(() => {
    vi.resetAllMocks();
    vi.useFakeTimers();
    window.IntersectionObserver = vi
      .fn()
      .mockImplementation(intersectionObserverMock);
  });

  it('should display success notification', async () => {
    const wrapper = factory();
    wrapper.vm.notifySuccess(0);
    vi.runAllTimers();
    await nextTick();
    expect(wrapper.find('.bms-notification--success').exists()).toBeTruthy();
  });
  it('should display error notification', async () => {
    const wrapper = factory();
    wrapper.vm.notifyError(0);
    vi.runAllTimers();
    await nextTick();
    expect(wrapper.find('.bms-notification--error').exists()).toBeTruthy();
  });

  it('should display success notification and hide it after some time', async () => {
    const wrapper = factory();
    wrapper.vm.notifySuccess(3000);
    vi.runAllTimers();
    await nextTick();
    expect(wrapper.find('.bms-notification--success').exists()).toBeFalsy();
  });
  it('should display error notification and hide it after some time', async () => {
    const wrapper = factory();
    wrapper.vm.notifyError(3000);
    vi.runAllTimers();
    await nextTick();
    expect(wrapper.find('.bms-notification--error').exists()).toBeFalsy();
    expect(wrapper.find('.ui-modal').exists()).toBeFalsy();
  });
  it('should display modal when click on the see details', async () => {
    const wrapper = factory();
    wrapper.vm.notifyError(0, 'details');
    vi.runAllTimers();
    await nextTick();
    expect(wrapper.find('.bms-notification--error').exists()).toBeTruthy();
    await wrapper.find('.details').trigger('click');
    expect(wrapper.find('.ui-modal').exists()).toBeTruthy();
  });
});
