<script setup>
import { Icon } from "@iconify/vue";
import { watchDebounced } from "@vueuse/core";
import { Effect, Option } from "effect";
import { Fetch } from "fx-fetch";
import { computed, nextTick, ref } 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 { interpolateMarkdown } from "../../../../table/utils/runtime";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from "../../../../ui/command";
import { Field, FieldLabel, FieldMessages } from "../../../../ui/field";
import { InputGroup, InputGroupAddon, InputGroupButton } 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 { useFieldValidation } from "../../../utils/validation";
import { useFormReadonly } from "../../../utils/readonly";
import { useFormState } from "../../../utils/state";
defineOptions({ name: "ShwfedComboboxSingleRemoteFieldRuntime" });
const props = defineProps({
  fieldId: { type: String, required: true },
  config: { type: null, required: true }
});
const { locale, t } = useI18n({
  inheritLocale: true,
  messages: {
    zh: {
      "combobox-single-search-placeholder": "\u641C\u7D22\u2026",
      "combobox-single-empty": "\u65E0\u5339\u914D\u9879",
      "combobox-single-loading": "\u52A0\u8F7D\u4E2D\u2026"
    },
    en: {
      "combobox-single-search-placeholder": "Search\u2026",
      "combobox-single-empty": "No matches",
      "combobox-single-loading": "Loading\u2026"
    },
    ja: {
      "combobox-single-search-placeholder": "\u691C\u7D22\u2026",
      "combobox-single-empty": "\u4E00\u81F4\u306A\u3057",
      "combobox-single-loading": "\u8AAD\u307F\u8FBC\u307F\u4E2D\u2026"
    }
  }
});
const { state, getAt, setAt, setAtSilent } = 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) : void 0
);
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 { isRequired, errors, warnings, visible } = useFieldValidation({
  fieldId: () => props.fieldId,
  config: () => props.config,
  $cel,
  locale: () => locale.value
});
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 json = ref(null);
const isLoading = ref(false);
const requestSignature = computed(() => {
  const expr = props.config.request;
  if (!expr) return null;
  try {
    const req = asRequest(Effect.runSync($cel(expr, { form: state.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.config.request;
  isLoading.value = true;
  const program = Effect.gen(function* () {
    const body = yield* fetchJsonOption(yield* $cel(expr, { form: state.value ?? {} }));
    return Option.getOrNull(body);
  });
  try {
    const result = await Effect.runPromise(Effect.provide(program, Fetch.layer));
    if (seq === fetchSeq) json.value = result;
  } catch {
    if (seq === fetchSeq) json.value = null;
  } finally {
    if (seq === fetchSeq) isLoading.value = false;
  }
}
const entries = computed(() => {
  let raw;
  try {
    raw = Effect.runSync($cel(props.config.options, { form: state.value ?? {}, json: json.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(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);
  }
});
let lastRequestSignature;
watchDebounced(
  requestSignature,
  () => {
    if (lastRequestSignature != null) {
      const path = props.config.binding;
      if (path == null) uncontrolled.value = void 0;
      else setAtSilent(path, void 0);
    }
    lastRequestSignature = requestSignature.value;
    void fetchOptions();
  },
  { debounce: 200, immediate: true }
);
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;
}
</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 }}<span
        v-if="isRequired"
        aria-hidden="true"
        class="text-red-600"
      > *</span>
    </FieldLabel>
    <div
      v-if="effectiveReadonly"
      class="min-h-9 py-1.5 text-sm text-zinc-700"
    >
      <Markdown
        v-if="selectedLabel"
        :source="selectedLabel"
      />
      <template v-else>
        —
      </template>
    </div>
    <Popover
      v-else
      v-model:open="open"
    >
      <PopoverAnchor as-child>
        <InputGroup
          class="group/combobox-single-remote"
          :data-disabled="isDisabled ? 'true' : void 0"
        >
          <PopoverTrigger as-child>
            <button
              :id="fieldId"
              type="button"
              :disabled="isDisabled"
              :data-value="!!selectedLabel"
              data-slot="input-group-control"
              class="peer flex h-9 min-w-0 flex-1 cursor-default items-center overflow-hidden rounded-none border-0 bg-transparent px-3 py-1 text-left text-sm text-zinc-700 outline-none disabled:cursor-not-allowed"
            >
              <Markdown
                v-if="selectedLabel"
                :source="selectedLabel"
                class="block truncate"
              />
              <span
                v-else-if="placeholderText"
                class="block truncate text-zinc-300"
              >{{ placeholderText }}</span>
            </button>
          </PopoverTrigger>
          <InputGroupAddon
            v-if="isLoading"
            align="inline-end"
            class="text-zinc-400"
          >
            <Icon
              icon="fluent:spinner-ios-20-regular"
              class="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="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>
            <!-- Zero candidates: still loading, the fetch failed, or the
                 endpoint returned nothing. `CommandEmpty` cannot cover this
                 — it only renders once a search query has filtered a
                 non-empty list down to zero — so the empty list is given an
                 explicit placeholder here. -->
            <div
              v-if="entries.length === 0"
              data-slot="combobox-single-remote-empty"
              class="py-6 text-center text-sm text-zinc-500"
            >
              {{ isLoading ? t("combobox-single-loading") : t("combobox-single-empty") }}
            </div>
            <template v-else>
              <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"
                >
                  <Markdown :source="entry.label" />
                </CommandItem>
              </CommandGroup>
            </template>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
    <FieldMessages
      v-if="visible"
      :errors="errors"
      :warnings="warnings"
    />
  </Field>
</template>
