<template>
  <label
      class="ais-label inline-flex gap-2.5 items-center"
      :class="classes"
  >
    <BaseCheckbox
        v-bind="modifiedProps"
        v-model="model"
        :name="name"
        :disabled="disabled"
    />
    <span v-if="$slots.default" class="flex gap-1.5 items-center">
      <AisIcon v-if="$props.icon" :icon="$props.icon" />
      <span>
        <slot />
      </span>
    </span>
  </label>
</template>

<script setup>
  import { ref, computed, inject } from 'vue'
  import { checkboxProps } from "@/components/checkbox/checkbox";
  import { iconProps } from "@c/icon/ais-icons";
  import BaseCheckbox from './BaseCheckbox.vue'
  import AisIcon from '@/components/icon/AisIcon.vue'
  import {expectedValues} from "@/util/prop-validators";
  import {
    CONTROL_MODEL, CONTROL_PARENT_UPDATE,
    CONTROL_NAME, CONTROL_SIZE, CONTROL_DISABLED,
  } from "@/util/controls";
  import {useSize} from "@/composables/useInjections";


  const props = defineProps({
    ...checkboxProps,
    ...iconProps,

    size: {
      type: String, required: false, default: undefined,
      validator: expectedValues('sm', 'md', 'lg')
    },
  })

  const emit = defineEmits([
    'update:modelValue'
  ])

  const modelValueRef = inject(CONTROL_MODEL, computed(() => props.modelValue))
  const updateParent = inject(CONTROL_PARENT_UPDATE, (val) => val)

  const model = computed({
    get() { return modelValueRef.value },

    set(newValue) {
      emit('update:modelValue', newValue)
      updateParent(newValue)
    }
  })

  const name = inject(CONTROL_NAME, computed(() => props.name))
  const size = useSize(props, 'md')
  const injectedDisabled = inject(CONTROL_DISABLED, computed(() => props.disabled))
  const disabled = computed(() => injectedDisabled.value || props.disabled)

  const sizeValues = {
    'sm': ['text-base'],
    'md': ['text-lg'],
    'lg': ['text-xl'],
  }

  const sizeClasses = computed(() => sizeValues[size.value])

  const classes = computed(() => {
    let classes = [...sizeClasses.value]

    if(disabled.value) classes.push('opacity-60', 'cursor-not-allowed')

    return classes
  })

  /**
   * We have to make sure the size prop isn't passed to
   * BaseCheckbox as it will become an illegal value on the
   * underlying DOM element
   */
  const modifiedProps = computed(() => {
    let mProps = { ...props }
    delete mProps.size
    return mProps
  })

</script>
