import { describe, it, expect } from 'vitest'
import { defineComponent, nextTick } from 'vue'
import { mount } from '@vue/test-utils'
import { createI18n } from 'vue-i18n'
import I18nValueEditor from '../I18nValueEditor.vue'

const ElTabsStub = defineComponent({
  name: 'ElTabs',
  props: {
    modelValue: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue'],
  template: '<div class="tabs"><slot /></div>'
})

const ElTabPaneStub = defineComponent({
  name: 'ElTabPane',
  props: {
    name: {
      type: String,
      default: ''
    },
    label: {
      type: String,
      default: ''
    }
  },
  template: '<div class="tab-pane" :data-name="name" :data-label="label"><slot /></div>'
})

const ElInputStub = defineComponent({
  name: 'ElInput',
  props: {
    modelValue: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue', 'input'],
  template: '<input :value="modelValue" @input="handleInput" />',
  methods: {
    handleInput(event: Event) {
      const target = event.target as HTMLInputElement
      this.$emit('update:modelValue', target.value)
      this.$emit('input', target.value)
    }
  }
})

describe('I18nValueEditor', () => {
  const i18n = createI18n({
    legacy: false,
    locale: 'en',
    messages: {
      en: {
        dictionary: {
          i18n: {
            zh: 'Chinese',
            en: 'English',
            zhPlaceholder: 'Chinese content',
            enPlaceholder: 'English content',
            hint: 'Fill at least one language.'
          }
        }
      }
    }
  })

  const mountEditor = (props?: Record<string, unknown>) => {
    return mount(I18nValueEditor, {
      props,
      global: {
        plugins: [i18n],
        stubs: {
          ElTabs: ElTabsStub,
          ElTabPane: ElTabPaneStub,
          ElInput: ElInputStub
        }
      }
    })
  }

  it('renders tabs for zh-CN and en', () => {
    const wrapper = mountEditor()
    const panes = wrapper.findAll('.tab-pane')

    expect(panes).toHaveLength(2)
    expect(panes[0].attributes('data-name')).toBe('zh-CN')
    expect(panes[1].attributes('data-name')).toBe('en')
  })

  it('validates at least one language is filled', async () => {
    const wrapper = mountEditor({ modelValue: {} })

    expect(wrapper.find('.i18n-hint').exists()).toBe(true)

    await wrapper.setProps({ modelValue: { 'zh-CN': '测试' } })
    await nextTick()

    expect(wrapper.find('.i18n-hint').exists()).toBe(false)
  })

  it('emits correct value object on input', async () => {
    const wrapper = mountEditor()
    const inputs = wrapper.findAll('input')

    await inputs[0].setValue('你好')

    const emitted = wrapper.emitted('update:modelValue')
    expect(emitted).toBeTruthy()
    expect(emitted?.[0][0]).toMatchObject({ 'zh-CN': '你好' })
  })
})
