<script setup>
import { computed } from "vue";
import { Checkbox } from "@/Components/ui/checkbox";

const props = defineProps({
  modelValue: { type: [Boolean, Array], required: true },
  value: { type: [String, Number], required: false },
  disabled: { type: Boolean, default: false },
  id: { type: String, required: false },
  class: { type: String, default: "" },
});

const emit = defineEmits(["update:modelValue"]);

const isChecked = computed(() => {
  if (Array.isArray(props.modelValue)) {
    return props.modelValue.includes(props.value);
  }
  return props.modelValue;
});

function handleChange(checked) {
  if (Array.isArray(props.modelValue)) {
    const newValue = [...props.modelValue];
    if (checked) {
      if (!newValue.includes(props.value)) {
        newValue.push(props.value);
      }
    } else {
      const index = newValue.indexOf(props.value);
      if (index > -1) {
        newValue.splice(index, 1);
      }
    }
    emit("update:modelValue", newValue);
  } else {
    emit("update:modelValue", checked);
  }
}
</script>

<template>
  <Checkbox
    :model-value="isChecked"
    @update:model-value="handleChange"
    :disabled="disabled"
    :id="id"
    :class="class"
  />
</template>
