<script setup>
import { Icon } from "@iconify/vue";
import { watchDebounced } from "@vueuse/core";
import { Effect, Option } from "effect";
import { Fetch } from "fx-fetch";
import { toast } from "vue-sonner";
import { computed, nextTick, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { asRequest, fetchJsonOption } from "../../../../../share/request";
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";
import { useSharedFetchLayer } from "../../../utils/shared-fetch";
defineOptions({ name: "ShwfedTableComboboxSingleRemoteOptionsRemoteRuntime" });
const props = defineProps({
  column: { type: null, required: true },
  ctx: { type: Object, 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",
      "combobox-single-loading": "\u52A0\u8F7D\u4E2D\u2026"
    },
    en: {
      "combobox-single-placeholder": "Select\u2026",
      "combobox-single-search-placeholder": "Search\u2026",
      "combobox-single-empty": "No matches",
      "combobox-single-loading": "Loading\u2026"
    },
    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",
      "combobox-single-loading": "\u8AAD\u307F\u8FBC\u307F\u4E2D\u2026"
    }
  }
});
const inherited = injectCELContext();
const $cel = (expression, context) => _rawCel(expression, { ...celBindings(inherited), ...context });
const eventChannel = useEventChannel();
const sharedFetchLayer = useSharedFetchLayer();
const row = computed(() => props.ctx.row.original);
const rowIndex = computed(() => props.ctx.row.index);
const placeholderText = computed(
  () => props.column.placeholder ? getLocalizedText(props.column.placeholder, locale.value) : t("combobox-single-placeholder")
);
function evalBool(expression, label) {
  if (!expression) return false;
  try {
    return Effect.runSync($cel(expression, { row: row.value, index: rowIndex.value })) === true;
  } catch (e) {
    console.error(`[shwfed-table] combobox-single.remote.options-remote ${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);
const json = ref(null);
const isLoading = ref(false);
const requestSignature = computed(() => {
  const expr = props.column.request;
  if (!expr) return null;
  try {
    const req = asRequest(Effect.runSync(
      $cel(expr, { row: row.value, index: rowIndex.value })
    ));
    return Option.isSome(req) ? JSON.stringify(req.value.describe()) : null;
  } catch {
    return null;
  }
});
let fetchSeq = 0;
async function fetchOptions() {
  const seq = ++fetchSeq;
  if (requestSignature.value == null) {
    json.value = null;
    isLoading.value = false;
    return;
  }
  const expr = props.column.request;
  isLoading.value = true;
  const program = Effect.gen(function* () {
    const json2 = yield* fetchJsonOption(yield* $cel(expr, { row: row.value, index: rowIndex.value }));
    return Option.getOrNull(json2);
  });
  try {
    const result = await Effect.runPromise(Effect.provide(program, sharedFetchLayer));
    if (seq === fetchSeq) json.value = result;
  } catch {
    if (seq === fetchSeq) json.value = null;
  } finally {
    if (seq === fetchSeq) isLoading.value = false;
  }
}
watchDebounced(
  requestSignature,
  () => {
    void fetchOptions();
  },
  { debounce: 200, immediate: true }
);
function valueOf(option) {
  try {
    return Effect.runSync($cel(props.column.optionValue, {
      row: row.value,
      index: rowIndex.value,
      option
    }));
  } catch (e) {
    console.error("[shwfed-table] combobox-single.remote.options-remote optionValue failed", e);
    return void 0;
  }
}
function labelOf(option) {
  const tpl = getLocalizedText(props.column.optionLabel, locale.value) ?? "";
  if (!tpl) return "";
  try {
    return interpolateMarkdown(tpl, $cel, { row: row.value, index: rowIndex.value, option });
  } catch (e) {
    console.error("[shwfed-table] combobox-single.remote.options-remote optionLabel failed", e);
    return "";
  }
}
const entries = computed(() => {
  let raw;
  try {
    raw = Effect.runSync($cel(props.column.options, {
      row: row.value,
      index: rowIndex.value,
      json: json.value
    }));
  } catch (e) {
    console.error("[shwfed-table] combobox-single.remote.options-remote options failed", e);
    return [];
  }
  if (!Array.isArray(raw)) return [];
  return raw.map((option, idx) => ({
    key: String(idx),
    label: labelOf(option),
    value: valueOf(option)
  }));
});
const cellValue = computed(() => props.ctx.cell.getValue());
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, cellValue.value))
);
const selectedKey = computed(() => selectedEntry.value?.key);
const selectedLabel = computed(() => selectedEntry.value?.label ?? "");
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, {
      row: row.value,
      index: rowIndex.value,
      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-single.remote.options-remote successMessage failed", e);
      }
    }
    await Effect.runPromise(dispatchTriggers(eventChannel, props.column.triggers, $cel));
  } catch (e) {
    console.error("[shwfed-table] combobox-single.remote.options-remote onChange failed", e);
    toast.error("\u8BF7\u6C42\u5931\u8D25");
  } finally {
    pending.value = false;
  }
}
function handleSelect(key) {
  if (typeof key !== "string") return;
  const entry = entries.value.find((e) => e.key === key);
  if (!entry) return;
  void nextTick().then(() => {
    open.value = false;
  });
  void submit(entry.value);
}
const showClear = computed(
  () => !isDisabled.value && selectedEntry.value !== void 0
);
function handleClear() {
  open.value = false;
  void submit(null);
}
const hoveredKey = ref(null);
watch(open, (isOpen) => {
  hoveredKey.value = isOpen ? entries.value[0]?.key ?? null : null;
});
</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"
    >
      {{ selectedLabel || "\u2014" }}
    </span>
    <Popover
      v-else
      v-model:open="open"
    >
      <PopoverAnchor as-child>
        <InputGroup
          class="group/combobox-single-remote 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="selectedLabel"
              :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 || isLoading"
            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-single-remote:opacity-100 focus-within:opacity-100"
          >
            <InputGroupButton
              size="icon-xs"
              data-slot="combobox-single-remote-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="selectedKey"
          :disabled="isDisabled"
          selection-behavior="toggle"
          @update:model-value="handleSelect"
        >
          <CommandInput :placeholder="t('combobox-single-search-placeholder')" />
          <CommandList>
            <div
              v-if="entries.length === 0"
              data-slot="combobox-single-remote-empty"
              class="py-3 text-center text-[0.75rem] text-zinc-500"
            >
              {{ isLoading ? t("combobox-single-loading") : t("combobox-single-empty") }}
            </div>
            <template v-else>
              <CommandEmpty class="py-3 text-center text-[0.75rem] 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"
                >
                  <Markdown :source="entry.label" />
                </CommandItem>
              </CommandGroup>
            </template>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  </div>
</template>
