<script setup lang="ts">
import type { CheckboxItem } from "@/components/ui/checkbox.types";
import log from "loglevel";

const props = defineProps<{
  checkboxItem: CheckboxItem<any>;
  disabled?: boolean;
}>();

const emit = defineEmits(["toggle"]);
const toggle = () => {
  emit("toggle");
};
const keydown = (e: KeyboardEvent) => {
  log.debug("keydown", e.type, e.key);
  if (e.key === " " && !props.disabled) {
    e.preventDefault();
    toggle();
  }
};
const input = (e: Event) => {
  const target = e.target as HTMLInputElement;
  log.debug("input", e.type, target.checked, target.value);
  emit("toggle");
};
</script>

<template>
  <!-- eslint-disable vue/no-v-html -->
  <div
    :class="{
      'opacity-50': disabled,
      'cursor-not-allowed': disabled,
      'cy-checked': checkboxItem.checked,
      'cy-unchecked': !checkboxItem.checked,
    }"
    :data-cy="`it-checkbox-${checkboxItem.value}`"
    class="inline-flex cursor-pointer"
  >
    <label
      class="flex h-8 items-center bg-contain bg-no-repeat pl-8 disabled:opacity-50"
      :class="
        checkboxItem.checked
          ? 'bg-[url(/static/icons/icon-checkbox-checked.svg)] hover:bg-[url(/static/icons/icon-checkbox-checked-hover.svg)]'
          : 'bg-[url(/static/icons/icon-checkbox-unchecked.svg)] hover:bg-[url(/static/icons/icon-checkbox-unchecked-hover.svg)]'
      "
      tabindex="0"
      @keydown.stop="keydown"
    >
      <input
        ref="checkbox"
        :checked="checkboxItem.checked"
        :value="checkboxItem.value"
        :disabled="disabled"
        :data-cy="`it-checkbox-${checkboxItem.value}-checkbox`"
        class="sr-only"
        type="checkbox"
        @keydown="keydown"
        @input="input"
      />
      <div class="ml-4 flex-col">
        <div v-if="checkboxItem.label" v-html="checkboxItem.label"></div>
        <div
          v-if="checkboxItem.subtitle"
          class="text-gray-900"
          v-html="checkboxItem.subtitle"
        ></div>
      </div>
    </label>
  </div>
</template>
