<script setup>
import { Icon } from "@iconify/vue";
import { computed, ref, watch } from "vue";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger
} from "../ui/dropdown-menu";
import { ExpressionEditor } from "../ui/expression-editor";
import { InputGroupButton } from "../ui/input-group";
import { DERIVED_MODE_LABELS, DERIVED_MODES } from "./utils/common";
defineOptions({ name: "ShwfedDerivedValueEditor" });
const props = defineProps({
  modelValue: { type: Object, required: false },
  resultType: { type: [String, Array], required: false },
  placeholder: { type: String, required: false }
});
const emit = defineEmits(["update:modelValue"]);
const MODE_ICONS = {
  formula: "fluent:calculator-20-regular",
  prefill: "fluent:sparkle-20-regular"
};
const mode = ref(props.modelValue?.mode ?? "formula");
watch(() => props.modelValue?.mode, (m) => {
  if (m) mode.value = m;
});
const expression = computed(() => props.modelValue?.expression ?? "");
function emitValue(nextMode, nextExpression) {
  emit("update:modelValue", nextExpression.length > 0 ? { mode: nextMode, expression: nextExpression } : void 0);
}
function onExpression(next) {
  emitValue(mode.value, next);
}
function selectMode(next) {
  mode.value = next;
  emitValue(next, expression.value);
}
</script>

<template>
  <ExpressionEditor
    :model-value="expression"
    :result-type="resultType"
    :placeholder="placeholder"
    class="min-h-10"
    @update:model-value="onExpression"
  >
    <template #leading>
      <DropdownMenu>
        <DropdownMenuTrigger as-child>
          <InputGroupButton
            size="xs"
            class="gap-1 text-zinc-600"
          >
            <Icon :icon="MODE_ICONS[mode]" />
            {{ DERIVED_MODE_LABELS[mode] }}
            <Icon
              icon="fluent:chevron-down-20-regular"
              class="text-zinc-400"
            />
          </InputGroupButton>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="start">
          <DropdownMenuItem
            v-for="m in DERIVED_MODES"
            :key="m"
            @select="selectMode(m)"
          >
            <Icon :icon="MODE_ICONS[m]" />
            {{ DERIVED_MODE_LABELS[m] }}
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </template>
  </ExpressionEditor>
</template>
