<script setup lang="ts">
import { toRefs, ref, reactive, watch } from 'vue'
import {
  RadioGroup,
  RadioGroupLabel,
  RadioGroupOption,
} from '@headlessui/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<any>(params.value['default'])
const disable = ref<boolean>(arg['disabled'] ?? false)
const emit = defineEmits(['input', 'fieldData', 'selectedCondition'])
const inputValues = ref<any>([])

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

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

  // Handle conditional data if with_condition is true.
  if (typeof arg['with_condition'] !== 'undefined' && arg['with_condition'] !== null) {
    if (arg['with_condition']) {
      const selectTriggerValue: any = {}
      selectTriggerValue[arg['id']] = newVal
      emit('selectedCondition', selectTriggerValue)
    }
  }
})
</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">
      <RadioGroup
        v-model="value"
      >
        <div class="stwlite-tw-inline-flex stwlite-tw-align-middle stwlite-tw-mt-4 stwlite-tw-space-x-2">
          <RadioGroupOption
            v-for="(option, optionkey) in arg['options']" 
            :key="optionkey" 
            v-slot="{ checked, active }"
            as="template"
            :disabled="disable"
            :value="optionkey"
          >
            <div
              :class="[ 'stwlite-tw-h-full stwlite-tw-relative stwlite-tw-flex stwlite-tw-cursor-pointer stwlite-tw-rounded-lg stwlite-tw-border stwlite-tw-p-3 stwlite-tw-shadow-sm focus:stwlite-tw-outline-none', checked ? 'stwlite-tw-border-blue-600 stwlite-tw-ring-2 stwlite-tw-ring-blue-600' : 'stwlite-tw-border-gray-300', active ? 'stwlite-tw-bg-blue-50' : 'stwlite-tw-bg-white' ]"
            >
              <div class="stwlite-tw-flex stwlite-tw-flex-col">
                <RadioGroupLabel as="span" class="stwlite-tw-font-medium stwlite-tw-text-gray-900">
                  {{ option }}
                </RadioGroupLabel>
              </div>
            </div>
          </RadioGroupOption>
        </div>
      </RadioGroup>
      <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>