<script setup lang="ts">
import { toRefs, ref } from 'vue'
import {
  LabelControl,
  Tooltip,
} from './index'
import {
  purifyHtml,
} from '@/helper'
import { useSettingsStore } from '@/stores/settings-store'
import { storeToRefs } from 'pinia'

const props = defineProps({
  params: {
    type: Object,
    required: true,
  },
})
const { params } = toRefs(props)
const settingsStore = useSettingsStore()
const {
  showPopup,
  componentUpgrade,
} = storeToRefs(settingsStore)

const arg = params.value
let defaultValue = false
if ( arg['default'] === 'yes' || arg['default'] === 'true') {
  defaultValue = true
}
const checked = ref<boolean>(defaultValue)
const disable = ref<boolean>(arg['disabled'] ?? false)
const emit = defineEmits(['fieldData'])
const inputValues = ref<any>([])

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

const emitValueChange = () => {
  if (typeof arg['pro'] !== 'undefined' && arg['pro'] !== null) {
    if (typeof arg['pro_on_active'] !== 'undefined' && arg['pro_on_active'] !== null) {
      if ( arg['pro_on_active'] && checked.value ) {
        showPopup.value = true
        checked.value = false
      }
    } else {
      showPopup.value = true
      checked.value = !checked.value
    }
    
    componentUpgrade.value = arg['pro']
  } else {
    inputValues.value[arg['id']] = checked.value ? 'yes' : 'no'
    emit('fieldData', inputValues.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">
      <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-space-x-2">
        <input
          :id="arg['id']"
          type="checkbox"
          class="stwlite-tw-h-4 stwlite-tw-w-4 stwlite-tw-rounded stwlite-tw-border-gray-300 stwlite-tw-text-blue-600 focus:stwlite-tw-ring-blue-500"
          v-model="checked"
          @change="emitValueChange"
        />
        <label :for="arg['id']" class="stwlite-tw-text-sm stwlite-tw-text-gray-700">{{ arg['input_label'] }}</label>
      </div>
      <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>