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

const props = defineProps({
  params: {
    type: Object,
    required: true,
  },
  conditionalValues: {
    type: Object,
    required: false,
    default: () => ({}),
  },
})
const emit = defineEmits(['conditionalData'])
const { params, conditionalValues } = toRefs(props)
const arg = params.value
const defaultVal = ref<string>(conditionalValues.value[arg['id']] ? conditionalValues.value[arg['id']] : arg['default'])
const showElement = reactive({
  check: defaultVal.value === 'yes' ? true : false,
})
const checkedLabel = ref<any>(arg['options']['yes'])
const unCheckedLabel = ref<any>(arg['options']['no'])
const switchValue = ref<any>([])

/**
 * Emit switch value
 * @param {any} value
 */
const switchChange = (value: any) => {
  defaultVal.value = (value) ? 'yes' : 'no'
  switchValue.value[arg['id']] = defaultVal.value
  showElement.check = value
  emit('conditionalData', switchValue.value)
}
</script>

<template>
  <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-justify-between">
    <div>
      <LabelControl :params="arg" />
      <p
        v-if="arg['description'] !== 'undefined'" 
        class="stwlite-tw-text-sm stwlite-tw-text-gray-600 stwlite-tw-mt-1"
        v-html="purifyHtml(arg?.['description'] ?? '')"
      />
    </div>
    <div class="stwlite-tw-flex stwlite-tw-items-center">
      <button
        type="button"
        :id="`${arg['id']}-btn`"
        @click="switchChange(!showElement.check)"
        :class="[ 'stwlite-tw-relative stwlite-tw-inline-flex stwlite-tw-h-6 stwlite-tw-w-11 stwlite-tw-items-center stwlite-tw-rounded-full stwlite-tw-transition-colors stwlite-tw-border-0', showElement.check ? 'stwlite-tw-bg-blue-600 stwlite-selected-btn-field' : 'stwlite-tw-bg-gray-200' ]"
      >
        <span
          :class="[ 'stwlite-tw-inline-block stwlite-tw-h-4 stwlite-tw-w-4 stwlite-tw-transform stwlite-tw-rounded-full stwlite-tw-bg-white stwlite-tw-transition-transform', showElement.check ? 'stwlite-tw-translate-x-4 stwlite-selected-label-field' : 'stwlite-tw-translate-x-0' ]"
        />
      </button>
      <span :id="`${arg['id']}-label`" class="stwlite-tw-ml-2 stwlite-tw-text-sm stwlite-tw-font-medium stwlite-tw-text-blue-600">
        {{ showElement.check ? checkedLabel : unCheckedLabel }}
      </span>
    </div>
  </div>
</template>