<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">
      <label>
        <span v-if="label !== undefined && label !== ''">
          {{ label }}
          <i v-if="required" class="form-item-alert">*</i>
        </span>
        <input
          :value="localValue"
          :type="type"
          :placeholder="placeholder"
          :disabled="disabled"
          :min="localMin"
          :max="localMax"
          @click="OnClick"
          @change="OnChange"
          @focus="OnFocus"
          @keydown="OnKeyDown"
          @keyup="OnKeyUp"
          :class="[
            invalidText !== undefined && invalidText !== '' ? 'invalid' : '',
            iclass || ''
          ]" />
        <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>
      </label>
    </slot>
  </div>
</template>
<script setup lang="ts">
  import { ref, computed, watch, onBeforeMount } from 'vue'
  import { useDateStore } from '@/stores/dateStore'
  const dateStore = useDateStore()

  export interface Props {
    type?: string
    label?: string
    disabled?: boolean
    modelValue: number | string | Date | null | undefined
    half?: boolean
    title?: string
    invalidText?: string
    description?: string
    placeholder?: string
    required?: boolean
    iclass?: string
    elclass?: string
    modelKey?: string
    min?: string | Date | null
    max?: string | Date | null
  }
  const props = withDefaults(defineProps<Props>(), {
    type: 'datetime-local',
    disabled: false,
    half: false,
    required: false
  })

  const emit = defineEmits([
    'update:modelValue',
    'change',
    'focus',
    'click',
    'keydown',
    'keyup'
  ])
  const localValue = ref<any>()
  const localMin = ref<string>()
  const localMax = ref<string>()

  const SetMin = () => {
    if (props.min !== undefined && props.min !== null) {
      if (props.type === 'datetime-local') {
        let dmin = new Date(props.min)
        dmin.setHours(0, 0, 0, 0)
        localMin.value = dateStore.dateFormat({
          date: dmin,
          pattern: 'yy-mm-dd-t',
          splitTime: 'T',
          splitDate: '-'
        })
      } else {
        localMin.value = dateStore.dateFormat({
          date: props.min,
          pattern: 'yy-mm-dd',
          splitDate: '-'
        })
      }
    }
  }

  const SetMax = () => {
    if (props.max !== undefined && props.max !== null) {
      if (props.type === 'datetime-local') {
        let dmax = new Date(props.max)
        dmax.setHours(0, 0, 0, 0)
        localMax.value = dateStore.dateFormat({
          date: props.max,
          pattern: 'yy-mm-dd-t',
          splitTime: 'T',
          splitDate: '-'
        })
      } else {
        localMax.value = dateStore.dateFormat({
          date: props.max,
          pattern: 'yy-mm-dd',
          splitDate: '-'
        })
      }
    }
  }

  if (props.type === 'date') {
    if (props.modelValue !== undefined && props.modelValue !== null) {
      if ((props.modelValue as string).includes('T')) {
        localValue.value = (props.modelValue as string).split('T')[0]
      } else {
        localValue.value = props.modelValue
      }
    }
  } else {
    localValue.value = props.modelValue
  }

  const InvalidMessageText = ref<Record<string,any>>({})
  const InvalidMessages = computed<string>(() => {
    let text = ''
    Object.keys(InvalidMessageText.value).forEach((k: string, i: number) => {
      text += InvalidMessageText.value[k] + ', '
    })
    return text
  })

  const OnChange = (e: Event) => {
    let val = (e.target as HTMLInputElement).value
    if (val !== undefined && val !== '') {
      if (localMin.value !== undefined) {
        if (val < localMin.value) {
          let min: string
          if (props.type === 'datetime-local') {
            min = dateStore.dateFormat({
              date: localMin.value,
              pattern: 'dd-mm-yy-t'
            })
          } else {
            min = dateStore.dateFormat({
              date: localMin.value,
              pattern: 'dd-mm-yy'
            })
          }
          InvalidMessageText.value[
            props.modelKey + 'Min'
          ] = `Girdiğiniz tarih ${min} tarihinden büyük olmalıdır.`
        } else {
          delete InvalidMessageText.value[props.modelKey + 'Min']
        }
      }
      if (localMax.value !== undefined) {
        if (val > localMax.value) {
          let max: string
          if (props.type === 'datetime-local') {
            max = dateStore.dateFormat({
              date: localMax.value,
              pattern: 'dd-mm-yy-t'
            })
          } else {
            max = dateStore.dateFormat({
              date: localMax.value,
              pattern: 'dd-mm-yy'
            })
          }
          InvalidMessageText.value[
            props.modelKey + 'Max'
          ] = `Girdiğiniz tarih ${max} tarihinden küçük olmalıdır.`
        } else {
          delete InvalidMessageText.value[props.modelKey + 'Max']
        }
      }
    }

    localValue.value = (e.target as HTMLInputElement).value
    emit('update:modelValue', localValue.value)
    emit('change', e)
  }
  const OnFocus = (e: Event) => {
    emit('focus', e)
  }
  const OnClick = (e: Event) => {
    emit('click', e)
  }
  const OnKeyDown = (e: Event) => {
    localValue.value = (e.target as HTMLInputElement).value
    emit('update:modelValue', localValue.value)
    emit('keydown', e)
  }
  const OnKeyUp = (e: Event) => {
    localValue.value = (e.target as HTMLInputElement).value
    if (props.required) {
      if (localValue.value !== undefined && localValue.value.length < 1) {
        InvalidMessageText.value[props.modelKey + 'Empty'] = 'Bu alan boş bırakılamaz'
      } else {
        delete InvalidMessageText.value[props.modelKey + 'Empty']
      }
    }
    emit('update:modelValue', localValue.value)
    emit('keyup', e)
  }
  watch(
    () => props.invalidText,
    () => {
      if (props.invalidText !== undefined && props.invalidText !== '') {
        InvalidMessageText.value = {}
        InvalidMessageText.value.invalid = props.invalidText
      } else {
        delete InvalidMessageText.value.invalid
      }
    }
  )
  watch(
    () => props.min,
    () => {
      if (props.min !== undefined && props.min !== '') {
        SetMin()
      }
    }
  )

  watch(
    () => props.max,
    () => {
      if (props.max !== undefined && props.max !== '') {
        SetMax()
      }
    }
  )

  onBeforeMount(() => {
    SetMin()
    SetMax()
  })
</script>
