import { mount } from '@vue/test-utils';
import { describe, it, expect } from 'vitest';
import MPasswordInput from './MPasswordInput.vue';

describe('MPasswordInput.vue', () => {
  it('renders correctly with default props', () => {
    const wrapper = mount(MPasswordInput, {
      props: {
        id: 'password-input',
      },
    });

    const input = wrapper.find('input');
    const toggleButton = wrapper.find('button[role="switch"]');

    expect(input.exists()).toBe(true);
    expect(input.attributes('type')).toBe('password');

    expect(toggleButton.exists()).toBe(true);
    expect(toggleButton.text()).toBe('Show');
  });

  it('toggles password visibility on button click', async () => {
    const wrapper = mount(MPasswordInput, {
      props: {
        id: 'password-input',
      },
    });

    const toggleButton = wrapper.find('button[role="switch"]');
    const input = wrapper.find('input');

    expect(input.attributes('type')).toBe('password');

    await toggleButton.trigger('click');

    expect(input.attributes('type')).toBe('text');
    expect(toggleButton.text()).toBe('Hide');

    await toggleButton.trigger('click');

    expect(input.attributes('type')).toBe('password');
    expect(toggleButton.text()).toBe('Show');
  });

  it('should update modelValue when input value changes', async () => {
    const wrapper = mount(MPasswordInput, {
      props: {
        id: 'password-input',
        modelValue: '',
      },
    });

    const input = wrapper.find('input');
    await input.setValue('newPassword123');

    expect(wrapper.emitted()['update:modelValue']).toBeTruthy();
    expect(wrapper.emitted()['update:modelValue'][0]).toEqual([
      'newPassword123',
    ]);
  });

  it('clears the input when the clear button is clicked', async () => {
    const wrapper = mount(MPasswordInput, {
      props: {
        id: 'password-input',
        modelValue: 'somePassword',
        isClearable: true,
        clearLabel: 'Clear content',
      },
    });

    const clearButton = wrapper.find('.mc-controls-options__button');

    await clearButton.trigger('click');

    expect(wrapper.emitted()['update:modelValue']).toBeTruthy();
    expect(wrapper.emitted()['update:modelValue'][0]).toEqual(['']);
  });

  it('disables the input when disabled prop is passed', () => {
    const wrapper = mount(MPasswordInput, {
      props: {
        id: 'password-input',
        disabled: true,
      },
    });

    const input = wrapper.find('input');

    expect(input.attributes('disabled')).toBeDefined();
  });

  it('applies invalid state when isInvalid prop is true', () => {
    const wrapper = mount(MPasswordInput, {
      props: {
        id: 'password-input',
        isInvalid: true,
      },
    });

    expect(wrapper.classes()).toContain('is-invalid');
  });
});
