<script setup>
import { computed, ref, watch } from "vue";
import ColorPicker from "primevue/colorpicker";
import BaseInputText from "./BaseInputText.vue";
import { isValidHexColor, normalizeHexColor } from "../../lib/themePalettes.js";

const props = defineProps({
  label: { type: String, default: "" },
  description: { type: String, default: "" },
  modelValue: { type: String, default: "" },
  disabled: { type: Boolean, default: false },
  id: { type: String, default: undefined },
});

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

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

const hexText = ref(props.modelValue || "");

watch(
  () => props.modelValue,
  (value) => {
    hexText.value = value || "";
  },
  { immediate: true },
);

const pickerValue = computed({
  get() {
    const normalized = normalizeHexColor(hexText.value);
    return normalized ? normalized.slice(1) : "3b82f6";
  },
  set(value) {
    const next = normalizeHexColor(
      typeof value === "string" && value.startsWith("#") ? value : `#${value}`,
    );
    if (!next) {
      return;
    }
    hexText.value = next;
    emit("update:modelValue", next);
    emit("change", next);
  },
});

function onHexInput(value) {
  hexText.value = value;
  if (!isValidHexColor(value)) {
    return;
  }
  const normalized = normalizeHexColor(value);
  emit("update:modelValue", normalized);
  emit("change", normalized);
}
</script>

<template>
  <div class="flex flex-col gap-3">
    <div v-if="label || description" class="flex flex-col">
      <label
        v-if="label"
        :for="inputId"
        class="block text-surface-950 dark:text-surface-0 text-md font-medium leading-7"
      >
        {{ label }}
      </label>
      <div
        v-if="description"
        class="mb-1 text-base font-normal leading-normal text-surface-500 dark:text-surface-400"
      >
        {{ description }}
      </div>
    </div>

    <div class="flex flex-wrap items-center gap-3">
      <ColorPicker
        v-model="pickerValue"
        format="hex"
        :disabled="disabled"
        :input-id="inputId"
      />
      <BaseInputText
        :id="`${inputId}-hex`"
        :model-value="hexText"
        class="max-w-[10rem]"
        placeholder="#3b82f6"
        :disabled="disabled"
        @update:model-value="onHexInput"
      />
    </div>
  </div>
</template>
