<template>
  <div class="form-check" :class="{ 'form-switch': toggleSwitch, 'form-check-reverse': labelFirst, disabled }">
    <input
      class="form-check-input"
      type="checkbox"
      ref="el"
      :role="toggleSwitch ? 'switch' : 'checkbox'"
      :checked="modelValue === true"
      :id="id"
      :disabled="disabled"
      @input="onChanged()"
    />
    <label class="form-check-label" :for="id" v-if="!!label"> {{ label }} </label>
  </div>
</template>

<script lang="ts">
import { useIds } from '@/composables';
const { getId } = useIds();
</script>

<script setup lang="ts">
import { ref, onMounted } from 'vue';

const props = defineProps({
  label: String,
  modelValue: [Boolean, null],
  id: {
    type: String,
    default: () => getId('checkbox'),
  },
  disabled: Boolean,
  indeterminate: Boolean,
  required: Boolean,
  labelFirst: Boolean,
  toggleSwitch: Boolean,
});
const emit = defineEmits(['update:modelValue']);

const el = ref<any>(null);

const setAndEmit = (val: boolean | null) => {
  if (val === null) {
    el.value.indeterminate = true;
  } else {
    el.value.indeterminate = false;
    // el.value.value = val;
  }
  emit('update:modelValue', val);
};

const onChanged = () => {
  if (!props.disabled) {
    let value: boolean | null;
    if (props.modelValue == null) {
      value = true;
    } else if (props.modelValue === true) {
      value = false;
    } else {
      if (props.indeterminate && !props.required) {
        value = null;
      } else {
        value = true;
      }
    }
    setAndEmit(value);
  }
};

onMounted(() => {
  if (props.indeterminate) {
    el.value.indeterminate = true;
  }
});
</script>

<style lang="scss">
@import '../../styles/mixins';

.form-check {
  &:not(.disabled) {
    input.form-check-input,
    label.form-check-label {
      cursor: pointer;
    }
  }
  label.form-check-label {
    @include noTextSelect();
  }
}
</style>
