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

interface Props {
  checkboxItem: CheckboxItem<any>;
  disabled?: boolean;
  iconCheckedTailwindClass?: string;
  iconUncheckedTailwindClass?: string;
}

const props = withDefaults(defineProps<Props>(), {
  disabled: false,
  iconCheckedTailwindClass: itCheckboxDefaultIconCheckedTailwindClass,
  iconUncheckedTailwindClass: itCheckboxDefaultIconUncheckedTailwindClass,
});

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 = () => {
  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
          ? props.iconCheckedTailwindClass
          : props.iconUncheckedTailwindClass
      "
      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>
