<script setup>
import { Icon } from "@iconify/vue";
import { Effect } from "effect";
import { Fetch } from "fx-fetch";
import { toast } from "vue-sonner";
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { cel as _rawCel } from "../../../../../utils/cel";
import { celBindings, injectCELContext } from "../../../../../utils/cel-context";
import { getLocalizedText } from "../../../../../share/locale";
import { dispatchTriggers, useEventChannel } from "../../../../../share/event-bus";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from "../../../../ui/command";
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "../../../../ui/input-group";
import { Markdown } from "../../../../ui/markdown";
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "../../../../ui/popover";
import { interpolateMarkdown } from "../../../utils/runtime";
defineOptions({ name: "ShwfedTableComboboxMultiRemoteOptionsStaticRuntime" });
const props = defineProps({
  column: { type: null, required: true },
  ctx: { type: Object, 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 inherited = injectCELContext();
const $cel = (expression, context) => _rawCel(expression, { ...celBindings(inherited), ...context });
const eventChannel = useEventChannel();
const placeholderText = computed(
  () => props.column.placeholder ? getLocalizedText(props.column.placeholder, locale.value) : t("combobox-multi-placeholder")
);
function evalBool(expression, label) {
  if (!expression) return false;
  try {
    return Effect.runSync($cel(expression)) === true;
  } catch (e) {
    console.error(`[shwfed-table] combobox-multi.remote.options-static ${label} failed`, e);
    return false;
  }
}
const isHidden = computed(() => evalBool(props.column.hidden, "hidden"));
const isDisabledByConfig = computed(() => evalBool(props.column.disabled, "disabled"));
const isReadonly = computed(() => evalBool(props.column.readonly, "readonly"));
const isInteractive = computed(() => !!props.column.onChange);
const pending = ref(false);
function safeInterpolate(tpl) {
  try {
    return interpolateMarkdown(tpl, $cel, {});
  } catch (e) {
    console.error("[shwfed-table] combobox-multi.remote.options-static label interpolation failed", e);
    return tpl;
  }
}
const entries = computed(
  () => (props.column.items ?? []).map((item) => {
    const labelTpl = getLocalizedText(item.label, locale.value) ?? "";
    const tooltipTpl = item.tooltip ? getLocalizedText(item.tooltip, locale.value) : void 0;
    return {
      key: item.id,
      value: item.value.value,
      label: labelTpl ? safeInterpolate(labelTpl) : "",
      tooltip: tooltipTpl ? safeInterpolate(tooltipTpl) : void 0
    };
  })
);
const cellValue = computed(() => {
  const raw = props.ctx.cell.getValue();
  return Array.isArray(raw) ? raw : [];
});
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 cellValue.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);
const isDisabled = computed(
  () => !isInteractive.value || isDisabledByConfig.value || pending.value
);
async function submit(next) {
  const { onChange, successMessage } = props.column;
  if (!onChange) return;
  pending.value = true;
  const program = Effect.gen(function* () {
    const builder = yield* $cel(onChange, { value: next });
    return yield* builder.json();
  });
  try {
    const body = await Effect.runPromise(Effect.provide(program, Fetch.layer));
    if (successMessage) {
      try {
        const message = Effect.runSync($cel(successMessage, { json: body }));
        if (message) toast.success(message);
      } catch (e) {
        console.error("[shwfed-table] combobox-multi.remote.options-static successMessage failed", e);
      }
    }
    await Effect.runPromise(dispatchTriggers(eventChannel, props.column.triggers));
  } catch (e) {
    console.error("[shwfed-table] combobox-multi.remote.options-static onChange failed", e);
    toast.error("\u8BF7\u6C42\u5931\u8D25");
  } finally {
    pending.value = 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);
  }
  void submit(mapped);
}
const showClear = computed(
  () => !isDisabled.value && selectedEntries.value.length > 0
);
function handleClear() {
  open.value = false;
  void submit([]);
}
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>
  <div class="p-[0.125rem] w-full">
    <span
      v-if="isHidden"
      class="block h-7 w-full"
    />
    <span
      v-else-if="isReadonly || !isInteractive"
      class="flex items-center h-7 w-full px-2 text-[0.75rem] text-zinc-700 truncate"
    >
      {{ triggerLabel || "\u2014" }}
    </span>
    <Popover
      v-else
      v-model:open="open"
    >
      <PopoverAnchor as-child>
        <InputGroup
          class="group/combobox-multi h-7 rounded border-zinc-200/30 hover:border-zinc-200 focus-within:border-zinc-200 transition-colors ease-out duration-180"
          :data-disabled="isDisabled ? 'true' : void 0"
        >
          <PopoverTrigger as-child>
            <InputGroupInput
              :model-value="triggerLabel"
              :disabled="isDisabled"
              :placeholder="placeholderText"
              class="h-7 text-[0.75rem] md:text-[0.75rem] px-2 cursor-pointer text-left"
              readonly
            />
          </PopoverTrigger>
          <InputGroupAddon
            v-if="pending"
            align="inline-end"
            class="text-zinc-400"
          >
            <Icon
              icon="fluent:spinner-ios-20-regular"
              class="size-3 animate-spin"
            />
          </InputGroupAddon>
          <InputGroupAddon
            v-else-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="size-4 text-zinc-500 hover:text-zinc-700"
              tabindex="-1"
              @mousedown.prevent
              @click.stop="handleClear"
            >
              <Icon
                icon="fluent:dismiss-20-regular"
                class="size-3"
              />
            </InputGroupButton>
          </InputGroupAddon>
        </InputGroup>
      </PopoverAnchor>
      <PopoverContent
        class="w-auto p-0 [&_[data-slot=command-input-wrapper]]:h-7 [&_[data-slot=command-input-wrapper]]:px-2 [&_[data-slot=command-input-wrapper]_svg]:size-3 [&_[data-slot=command-input]]:h-7 [&_[data-slot=command-input]]:py-0 [&_[data-slot=command-input]]:text-[0.75rem] [&_[data-slot=command-item]]:px-2 [&_[data-slot=command-item]]:py-1 [&_[data-slot=command-item]]:text-[0.75rem]"
        :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-3 text-center text-[0.75rem] text-zinc-500">
              {{ t("combobox-multi-empty") }}
            </CommandEmpty>
            <CommandGroup>
              <CommandItem
                v-for="entry in entries"
                :key="entry.key"
                :value="entry.key"
                @mouseenter="hoveredKey = entry.key"
                @focus="hoveredKey = entry.key"
              >
                <span class="flex-1">{{ entry.label }}</span>
                <Icon
                  v-if="selectedKeySet.has(entry.key)"
                  icon="fluent:checkmark-20-regular"
                  class="size-3 text-zinc-700"
                />
              </CommandItem>
            </CommandGroup>
          </CommandList>
          <div
            v-if="anyHasTooltip && hoveredTooltip"
            class="border-t border-zinc-200 px-2 py-1.5"
          >
            <Markdown
              :source="hoveredTooltip"
              block
              class="prose prose-xs prose-zinc"
            />
          </div>
        </Command>
      </PopoverContent>
    </Popover>
  </div>
</template>
