<template>
  <div :class="['form-item', half ? 'form-item-half' : '', elclass || '']">
    <span class="form-item-title" v-if="title !== undefined && title !== ''">
      {{ title }}
    </span>
    <slot name="input">
      <span v-if="label !== undefined && label !== ''" class="summer-label">
        {{ label }}
        <i v-if="required" class="form-item-alert">*</i>
      </span>
      <div :ref="'summerContainer' + rnd" class="summer-editor"></div>
      <span
        class="form-item-alert"
        v-if="InvalidMessages.length > 0 && InvalidMessages !== ''">
        {{ InvalidMessages }}
      </span>
      <span
        class="form-item-description"
        v-if="description !== undefined && description !== ''">
        {{ description }}
      </span>
    </slot>
  </div>
</template>
<script setup lang="ts">
  import {
    ref,
    reactive,
    computed,
    onMounted,
    useTemplateRef,
    watch,
    onBeforeUnmount
  } from 'vue'
  import $ from 'jquery'
  import 'summernote/dist/summernote-lite.min.css'
  import 'summernote/dist/summernote-lite.min.js'
  //import SummernoteEditor from 'vue3-summernote-editor'

  export interface Props {
    label?: string
    disabled?: boolean
    modelValue: string
    half?: boolean
    title?: string
    invalidText?: string
    description?: string
    placeholder?: string
    required?: boolean
    maxlength?: string
    minlength?: string
    iclass?: string
    elclass?: string
    modelKey?: string
  }
  const props = withDefaults(defineProps<Props>(), {
    disabled: false,
    half: false,
    required: false,
    placeholder: ''
  })

  const emit = defineEmits(['update:modelValue', 'change', 'text-change'])
  const rnd = ref<number>(Number(Math.random() * 10000000))
  const editorElement = useTemplateRef<any>('summerContainer' + rnd.value)
  const editor = ref<any>(null)

  const localValue = ref<string>(props.modelValue)

  const InvalidMessageText = ref<Record<string, any>>({})
  const InvalidMessages = computed(() => {
    let text = ''
    Object.keys(InvalidMessageText.value).forEach((k: string, i: number) => {
      text += InvalidMessageText.value[k] + ', '
    })
    return text
  })
  const SetupEditor = async () => {
    await InitializeEditor()
    SetContent()
  }
  const InitializeEditor = async () => {
    if (editorElement.value) {
      editor.value = $(editorElement.value).summernote({
        height: 300,
        codeviewFilter: false,
        codeviewIframeFilter: false,
        toolbar: [
          ['style', ['style']],
          [
            'font',
            [
              'bold',
              'italic',
              'underline',
              'strikethrough',
              'superscript',
              'subscript',
              'clear'
            ]
          ],
          ['fontname', ['fontname']],
          ['color', ['color']],
          ['para', ['ul', 'ol', 'paragraph']],
          ['height', ['height']],
          ['table', ['table']],
          ['insert', ['link', 'picture', 'video']],
          ['view', ['fullscreen', 'codeview', 'undo', 'redo', 'help']]
        ],
        callbacks: {
          onChange: (content: any, e: any) => {
            localValue.value = content
            OnTextChange()
            emit('update:modelValue', localValue.value)
            emit('change', e)
          },
          onInit: () => {}
        }
      })
    }
  }

  const SetContent = () => {
    if (props.modelValue) $(editorElement.value).summernote('code', props.modelValue)
  }

  const OnTextChange = () => {
    if (props.minlength !== undefined) {
      if (localValue.value.length < Number(props.minlength)) {
        InvalidMessageText.value.minlength = `Girdiğiniz bilgi en az ${props.minlength} karakter uzunluğunda olmalı`
      } else {
        delete InvalidMessageText.value.minlength
      }
    }
  }

  onMounted(async () => {
    SetupEditor()
  })

  watch(
    () => props.invalidText,
    () => {
      if (props.invalidText !== undefined && props.invalidText !== '') {
        InvalidMessageText.value.invalid = props.invalidText
      } else {
        delete InvalidMessageText.value.invalid
      }
    }
  )
</script>
<style>
  .summer-label {
    width: 100%;
  }
  .summer-editor {
    width: 100%;
  }
  .note-editor {
    width: 100%;
  }
  .note-editor.note-frame.fullscreen {
    background-color: #fff;
  }
  .note-color.open .note-dropdown-menu {
    display: flex;
  }
  .note-editor .note-toolbar .note-color-palette div .note-color-btn {
    min-height: inherit;
  }
  .note-editable ul {
    list-style-type: inherit;
    list-style-image: inherit;
    margin: inherit;
    padding: inherit;
  }
  .note-editable ul li {
    list-style-type: inherit;
    list-style-image: inherit;
  }
  .note-editable ol li {
    list-style-type: inherit;
    list-style-image: inherit;
  }
</style>
