<script setup>
import { Icon } from "@iconify/vue";
import { Effect } from "effect";
import { computed } 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 { Field, FieldLabel, FieldMessages } from "../../../../ui/field";
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "../../../../ui/input-group";
import { Markdown } from "../../../../ui/markdown";
import { DEFAULT_FIELD_ORIENTATION } from "../../../utils/common";
import { useFieldValue } from "../../../utils/field-value";
import { useFieldValidation } from "../../../utils/validation";
import { useFormReadonly } from "../../../utils/readonly";
import { useFormState } from "../../../utils/state";
defineOptions({ name: "ShwfedTextFieldRuntime" });
const props = defineProps({
  fieldId: { type: String, required: true },
  config: { type: null, required: true }
});
const { locale } = useI18n();
const { state } = 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 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");
const { draft, commit } = useFieldValue({
  binding: () => props.config.binding,
  fromState: (raw) => raw == null ? "" : String(raw),
  toState: (next) => next.length === 0 ? null : next
});
const { isRequired, errors, warnings, visible } = useFieldValidation({
  fieldId: () => props.fieldId,
  config: () => props.config,
  $cel,
  locale: () => locale.value
});
const showClear = computed(() => !isDisabled.value && draft.value.length > 0);
function handleClear() {
  draft.value = "";
  commit();
}
</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"
    >
      {{ draft || "\u2014" }}
    </div>
    <InputGroup
      v-else
      class="group/text-field"
    >
      <InputGroupInput
        :id="fieldId"
        v-model="draft"
        :placeholder="placeholderText"
        :disabled="isDisabled"
        @blur="commit"
        @keydown.enter="commit"
      />
      <InputGroupAddon
        v-if="showClear"
        align="inline-end"
        class="[@media(hover:hover)]:opacity-0 transition-opacity group-hover/text-field:opacity-100 focus-within:opacity-100"
      >
        <InputGroupButton
          size="icon-xs"
          data-slot="text-field-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>
    <FieldMessages
      v-if="visible"
      :errors="errors"
      :warnings="warnings"
    />
  </Field>
</template>
