<script setup>
import { Icon } from "@iconify/vue";
import { Effect } from "effect";
import { computed, ref } 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: "ShwfedComboboxMultiFieldRuntime" });
const props = defineProps({
  fieldId: { type: String, required: true },
  config: { type: null, required: true }
});
const { locale, t } = useI18n({
  inheritLocale: true,
  messages: {
    zh: {
      "combobox-multi-placeholder": "\u8BF7\u9009\u62E9",
      "combobox-multi-search-placeholder": "\u641C\u7D22\u2026",
      "combobox-multi-empty": "\u65E0\u5339\u914D\u9879"
    },
    en: {
      "combobox-multi-placeholder": "Select\u2026",
      "combobox-multi-search-placeholder": "Search\u2026",
      "combobox-multi-empty": "No matches"
    },
    ja: {
      "combobox-multi-placeholder": "\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044",
      "combobox-multi-search-placeholder": "\u691C\u7D22\u2026",
      "combobox-multi-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-multi-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 valueOf(option) {
  try {
    return Effect.runSync($cel(props.config.optionValue, { form: state.value ?? {}, option }));
  } catch (err) {
    console.error(`[shwfed-form] failed to evaluate optionValue for ${props.fieldId}:`, err);
    return void 0;
  }
}
function labelOf(option) {
  const tpl = getLocalizedText(props.config.optionLabel, locale.value) ?? "";
  if (!tpl) return "";
  return interpolateMarkdown(tpl, $cel, { form: state.value ?? {}, option });
}
const entries = computed(() => {
  let raw;
  try {
    raw = Effect.runSync($cel(props.config.options, { form: state.value ?? {} }));
  } catch (err) {
    console.error(`[shwfed-form] failed to evaluate options for ${props.fieldId}:`, err);
    return [];
  }
  if (!Array.isArray(raw)) return [];
  return raw.map((option, idx) => ({
    key: String(idx),
    label: labelOf(option),
    value: valueOf(option)
  }));
});
const uncontrolled = ref([]);
const model = computed({
  get: () => {
    const path = props.config.binding;
    const raw = path == null ? uncontrolled.value : getAt(path);
    return Array.isArray(raw) ? raw : [];
  },
  set: (next) => {
    const arr = Array.isArray(next) ? next : [];
    const path = props.config.binding;
    if (path == null) {
      uncontrolled.value = arr;
      return;
    }
    setAt(path, arr);
  }
});
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 selectedEntries = computed(() => {
  const list = [];
  for (const v of model.value) {
    const entry = entries.value.find((e) => isEqual(e.value, v));
    if (entry) list.push(entry);
  }
  return list;
});
const selectedKeys = computed(() => selectedEntries.value.map((e) => e.key));
const selectedKeySet = computed(() => new Set(selectedKeys.value));
const triggerLabel = computed(() => {
  const arr = selectedEntries.value;
  if (arr.length === 0) return "";
  if (arr.length === 1) return arr[0].label;
  return `${arr[0].label} +${arr.length - 1}`;
});
const open = ref(false);
function handleSelect(next) {
  const keys = Array.isArray(next) ? next.filter((k) => typeof k === "string") : [];
  const mapped = [];
  for (const key of keys) {
    const entry = entries.value.find((e) => e.key === key);
    if (entry) mapped.push(entry.value);
  }
  model.value = mapped;
}
const showClear = computed(
  () => !isDisabled.value && selectedEntries.value.length > 0
);
function handleClear() {
  model.value = [];
  open.value = false;
}
</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"
    >
      {{ triggerLabel || "\u2014" }}
    </div>
    <Popover
      v-else
      v-model:open="open"
    >
      <PopoverAnchor as-child>
        <InputGroup
          class="group/combobox-multi"
          :data-disabled="isDisabled ? 'true' : void 0"
        >
          <PopoverTrigger as-child>
            <InputGroupInput
              :id="fieldId"
              :model-value="triggerLabel"
              :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-multi:opacity-100 focus-within:opacity-100"
          >
            <InputGroupButton
              size="icon-xs"
              data-slot="combobox-multi-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="selectedKeys"
          :multiple="true"
          :disabled="isDisabled"
          @update:model-value="handleSelect"
        >
          <CommandInput :placeholder="t('combobox-multi-search-placeholder')" />
          <CommandList>
            <CommandEmpty class="py-6 text-center text-sm text-zinc-500">
              {{ t("combobox-multi-empty") }}
            </CommandEmpty>
            <CommandGroup>
              <CommandItem
                v-for="entry in entries"
                :key="entry.key"
                :value="entry.key"
              >
                <span class="flex-1">{{ entry.label }}</span>
                <Icon
                  v-if="selectedKeySet.has(entry.key)"
                  icon="fluent:checkmark-20-regular"
                  class="size-4 text-zinc-700"
                />
              </CommandItem>
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  </Field>
</template>
