<script setup>
import { Icon } from "@iconify/vue";
import { Effect } from "effect";
import { computed, nextTick, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { cel as _rawCel } from "../../../../../utils/cel";
import { celBindings, injectCELContext } from "../../../../../utils/cel-context";
import { interpolateMarkdown } from "../../../../table/utils/runtime";
import { getLocalizedText } from "../../../../../share/locale";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from "../../../../ui/command";
import { Field, FieldLabel } from "../../../../ui/field";
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "../../../../ui/input-group";
import { Markdown } from "../../../../ui/markdown";
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "../../../../ui/popover";
import { DEFAULT_FIELD_ORIENTATION } from "../../../utils/common";
import { useFormReadonly } from "../../../utils/readonly";
import { useFormState } from "../../../utils/state";
defineOptions({ name: "ShwfedComboboxSingleFieldRuntime" });
const props = defineProps({
  fieldId: { type: String, required: true },
  config: { type: null, required: true }
});
const { locale, t } = useI18n({
  inheritLocale: true,
  messages: {
    zh: {
      "combobox-single-placeholder": "\u8BF7\u9009\u62E9",
      "combobox-single-search-placeholder": "\u641C\u7D22\u2026",
      "combobox-single-empty": "\u65E0\u5339\u914D\u9879"
    },
    en: {
      "combobox-single-placeholder": "Select\u2026",
      "combobox-single-search-placeholder": "Search\u2026",
      "combobox-single-empty": "No matches"
    },
    ja: {
      "combobox-single-placeholder": "\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044",
      "combobox-single-search-placeholder": "\u691C\u7D22\u2026",
      "combobox-single-empty": "\u4E00\u81F4\u306A\u3057"
    }
  }
});
const { state, getAt, setAt } = useFormState();
const inherited = injectCELContext();
const $cel = (expression, context) => _rawCel(expression, { ...celBindings(inherited), ...context });
const labelText = computed(() => getLocalizedText(props.config.label, locale.value));
const placeholderText = computed(
  () => props.config.placeholder ? getLocalizedText(props.config.placeholder, locale.value) : t("combobox-single-placeholder")
);
const tooltipText = computed(
  () => props.config.tooltip ? getLocalizedText(props.config.tooltip, locale.value) : void 0
);
function evalBool(expression, label) {
  if (!expression) return false;
  try {
    return Effect.runSync($cel(expression, { form: state.value ?? {} }));
  } catch (err) {
    console.error(`[shwfed-form] failed to evaluate ${label} for ${props.fieldId}:`, err);
    return false;
  }
}
const isDisabled = computed(() => evalBool(props.config.disabled, "disabled"));
const formReadonly = useFormReadonly();
const isReadonly = computed(
  () => props.config.readonly != null ? evalBool(props.config.readonly, "readonly") : formReadonly.value
);
const effectiveReadonly = computed(() => isReadonly.value || props.config.derived?.mode === "formula");
function safeInterpolate(tpl, ctx) {
  try {
    return interpolateMarkdown(tpl, $cel, ctx);
  } catch (err) {
    console.error(`[shwfed-form] failed to interpolate option text for ${props.fieldId}:`, err);
    return tpl;
  }
}
const entries = computed(
  () => (props.config.items ?? []).map((item) => {
    const labelTpl = getLocalizedText(item.label, locale.value) ?? "";
    const tooltipTpl = item.tooltip ? getLocalizedText(item.tooltip, locale.value) : void 0;
    const ctx = { form: state.value ?? {} };
    return {
      key: item.id,
      value: item.value.value,
      label: labelTpl ? safeInterpolate(labelTpl, ctx) : "",
      tooltip: tooltipTpl ? safeInterpolate(tooltipTpl, ctx) : void 0
    };
  })
);
const uncontrolled = ref(void 0);
const model = computed({
  get: () => {
    const path = props.config.binding;
    if (path == null) return uncontrolled.value;
    return getAt(path);
  },
  set: (next) => {
    const path = props.config.binding;
    if (path == null) {
      uncontrolled.value = next;
      return;
    }
    setAt(path, next);
  }
});
function isEqual(a, b) {
  if (a === b) return true;
  if (a == null || b == null) return false;
  if (typeof a === "object" && typeof b === "object") {
    try {
      return JSON.stringify(a) === JSON.stringify(b);
    } catch {
      return false;
    }
  }
  return false;
}
const selectedEntry = computed(
  () => entries.value.find((entry) => isEqual(entry.value, model.value))
);
const selectedKey = computed(() => selectedEntry.value?.key);
const selectedLabel = computed(() => selectedEntry.value?.label ?? "");
const open = ref(false);
function handleSelect(key) {
  if (typeof key !== "string") return;
  const entry = entries.value.find((e) => e.key === key);
  if (!entry) return;
  model.value = entry.value;
  void nextTick().then(() => {
    open.value = false;
  });
}
const showClear = computed(
  () => !isDisabled.value && selectedEntry.value !== void 0
);
function handleClear() {
  model.value = void 0;
  open.value = false;
}
const hoveredKey = ref(null);
watch(open, (isOpen) => {
  hoveredKey.value = isOpen ? entries.value[0]?.key ?? null : null;
});
const hoveredEntry = computed(
  () => entries.value.find((e) => e.key === hoveredKey.value)
);
const hoveredTooltip = computed(() => hoveredEntry.value?.tooltip);
const anyHasTooltip = computed(
  () => entries.value.some((e) => e.tooltip != null && e.tooltip.length > 0)
);
</script>

<template>
  <Field
    :orientation="config.orientation ?? DEFAULT_FIELD_ORIENTATION"
    :data-disabled="isDisabled || void 0"
  >
    <FieldLabel
      v-if="labelText"
      :for="fieldId"
      class="text-xs text-zinc-500"
    >
      <template
        v-if="tooltipText"
        #tooltip
      >
        <Markdown
          :source="tooltipText"
          class="prose prose-xs prose-zinc"
        />
      </template>
      {{ labelText }}
    </FieldLabel>
    <div
      v-if="effectiveReadonly"
      class="min-h-9 py-1.5 text-sm text-zinc-700"
    >
      {{ selectedLabel || "\u2014" }}
    </div>
    <Popover
      v-else
      v-model:open="open"
    >
      <PopoverAnchor as-child>
        <InputGroup
          class="group/combobox-single"
          :data-disabled="isDisabled ? 'true' : void 0"
        >
          <PopoverTrigger as-child>
            <InputGroupInput
              :id="fieldId"
              :model-value="selectedLabel"
              :disabled="isDisabled"
              :placeholder="placeholderText"
              class="cursor-pointer text-left"
              readonly
            />
          </PopoverTrigger>
          <InputGroupAddon
            v-if="showClear"
            align="inline-end"
            class="[@media(hover:hover)]:opacity-0 transition-opacity group-hover/combobox-single:opacity-100 focus-within:opacity-100"
          >
            <InputGroupButton
              size="icon-xs"
              data-slot="combobox-single-clear"
              class="text-zinc-500 hover:text-zinc-700"
              tabindex="-1"
              @mousedown.prevent
              @click.stop="handleClear"
            >
              <Icon icon="fluent:dismiss-20-regular" />
            </InputGroupButton>
          </InputGroupAddon>
        </InputGroup>
      </PopoverAnchor>
      <PopoverContent
        class="p-0"
        :style="{ width: 'var(--reka-popover-trigger-width)' }"
      >
        <Command
          :model-value="selectedKey"
          :disabled="isDisabled"
          selection-behavior="toggle"
          @update:model-value="handleSelect"
        >
          <CommandInput :placeholder="t('combobox-single-search-placeholder')" />
          <CommandList>
            <CommandEmpty class="py-6 text-center text-sm text-zinc-500">
              {{ t("combobox-single-empty") }}
            </CommandEmpty>
            <CommandGroup>
              <CommandItem
                v-for="entry in entries"
                :key="entry.key"
                :value="entry.key"
                @mouseenter="hoveredKey = entry.key"
                @focus="hoveredKey = entry.key"
              >
                {{ entry.label }}
              </CommandItem>
            </CommandGroup>
          </CommandList>
          <div
            v-if="anyHasTooltip && hoveredTooltip"
            class="border-t border-zinc-200 px-3 py-2"
          >
            <Markdown
              :source="hoveredTooltip"
              block
              class="prose prose-sm prose-zinc"
            />
          </div>
        </Command>
      </PopoverContent>
    </Popover>
  </Field>
</template>
