<script setup>
/**
 * Toggle switch — use this instead of PrimeVue ToggleSwitch in views.
 */
import { computed, ref } from "vue";
import ToggleSwitch from "primevue/toggleswitch";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  label: { type: String, default: "" },
  labelPosition: {
    type: String,
    default: "top",
    validator: (value) => ["top", "left"].includes(value),
  },
  disabled: { type: Boolean, default: false },
  id: { type: String, default: undefined },
  class: { type: [String, Object, Array], default: "" },
});

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

const fallbackId = ref(`base-toggle-${Math.random().toString(36).slice(2, 11)}`);
const inputId = computed(() => props.id ?? fallbackId.value);

const labelClass =
  "block text-md font-medium leading-6 text-surface-950 dark:text-surface-0";
</script>

<template>
  <div
    v-if="label && labelPosition === 'left'"
    class="flex items-center gap-2"
    :class="props['class']"
  >
    <label :for="inputId" :class="[labelClass, 'mb-0 shrink-0']">
      {{ label }}
    </label>
    <ToggleSwitch
      :input-id="inputId"
      :model-value="modelValue"
      :disabled="disabled"
      @update:model-value="emit('update:modelValue', $event)"
    />
  </div>
  <div v-else class="flex flex-col" :class="props['class']">
    <div v-if="label" class="mb-1 flex flex-col">
      <label :for="inputId" :class="labelClass">
        {{ label }}
      </label>
    </div>
    <ToggleSwitch
      :input-id="inputId"
      :model-value="modelValue"
      :disabled="disabled"
      @update:model-value="emit('update:modelValue', $event)"
    />
  </div>
</template>
