<script setup lang="ts">
import { toRefs, ref } from 'vue'
import {
  LabelControl,
  Tooltip,
} from './index'
import {
  purifyHtml,
} from '@/helper'

const props = defineProps({
  params: {
    type: Object,
    required: true,
  },
})
const { params } = toRefs(props)
const arg = params.value
const value = ref<string>(arg['default'] ?? '')
const step = ref<number>(arg['step'] ?? 1)
const disable = ref<boolean>(arg['disabled'] ?? false)
const emit = defineEmits(['input', 'fieldData', 'previewRef'])
const inputValues = ref<any>([])
const previewRef = ref<any>([])

// Set for default value.
if (value.value !== '' && !disable.value) {
  inputValues.value[arg['id']] = value.value
  emit('fieldData', inputValues.value)
}

const emitValueChange = () => {
  inputValues.value[arg['id']] = value
  emit('fieldData', inputValues.value)

  previewRef.value[arg['id']] = inputValues.value
  emit('previewRef', previewRef.value)
}
</script>

<template>
  <div>
    <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-mb-2 stwlite-tw-gap-2">
      <LabelControl
        :params="arg"
      />
    </div>
    <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-mb-2 stwlite-tw-gap-2">
      <input
        v-model="value"
        :id="arg['id']"
        :name="arg['id']"
        :disabled="disable"
        :placeholder="arg['placeholder']"
        type="number"
        @input="emitValueChange"
        :min="arg['min']"
        :max="arg['max']"
        :step="step"
        :class="[ 'stwlite-tw-block stwlite-tw-w-full stwlite-tw-max-w-xs stwlite-tw-px-3 stwlite-tw-py-2 stwlite-tw-border stwlite-tw-border-gray-300 stwlite-tw-rounded-md stwlite-tw-shadow-sm stwlite-tw-placeholder-gray-400 focus:stwlite-tw-outline-none focus:stwlite-tw-ring-2 focus:stwlite-tw-ring-blue-500 focus:stwlite-tw-border-blue-500', disable ? 'stwlite-tw-bg-gray-100 stwlite-tw-text-gray-500 stwlite-tw-cursor-not-allowed' : 'stwlite-tw-bg-white stwlite-tw-text-gray-900' ]"
      />
      <Tooltip :params="arg" />
    </div>
    <p v-if="arg['description'] !== 'undefined'" class="stwlite-tw-text-sm stwlite-tw-text-gray-600 stwlite-tw-mt-2" v-html="purifyHtml(arg?.['description'] ?? '')" />
  </div>
</template>

<style scoped lang="scss">
input[type="number"] {
  padding-right: 0.75rem;
  padding-left: 0.75rem;
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
  background-color: rgb(255 255 255 / 1);
  border-color: rgb(209 213 219 / 1);
  border-width: 1px;
  border-radius: 0.375rem;
}
</style>