<script setup>
import { Icon } from "@iconify/vue";
import { Effect } from "effect";
import { computed, nextTick } 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, InputGroupNumberField } 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: "ShwfedNumberFieldRuntime" });
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;
  }
}
function evalNumber(expression, label) {
  if (!expression) return void 0;
  try {
    const result = Effect.runSync($cel(expression, { form: state.value ?? {} }));
    return typeof result === "number" && Number.isFinite(result) ? result : void 0;
  } catch (err) {
    console.error(`[shwfed-form] failed to evaluate ${label} for ${props.fieldId}:`, err);
    return void 0;
  }
}
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 minValue = computed(() => evalNumber(props.config.min, "min"));
const maxValue = computed(() => evalNumber(props.config.max, "max"));
const { isRequired, errors, warnings, visible } = useFieldValidation({
  fieldId: () => props.fieldId,
  config: () => props.config,
  $cel,
  locale: () => locale.value
});
const formatOptions = computed(() => ({
  useGrouping: false,
  maximumFractionDigits: 20
}));
const { draft, commit } = useFieldValue({
  binding: () => props.config.binding,
  fromState: (raw) => {
    if (typeof raw === "number" && Number.isFinite(raw)) return raw;
    if (typeof raw === "string" && raw.length > 0) {
      const n = Number(raw);
      return Number.isFinite(n) ? n : void 0;
    }
    return void 0;
  },
  toState: (next) => {
    if (typeof next !== "number" || !Number.isFinite(next)) return null;
    return props.config.valueAsString ? String(next) : next;
  }
});
function applyRounding(n, precision, mode) {
  const factor = 10 ** precision;
  switch (mode) {
    case "floor":
      return Math.floor(n * factor) / factor;
    case "ceil":
      return Math.ceil(n * factor) / factor;
    default:
      return Math.round(n * factor) / factor;
  }
}
const showClear = computed(() => !isDisabled.value && draft.value !== void 0);
function handleClear() {
  draft.value = void 0;
  commit();
}
async function onBlur() {
  await nextTick();
  const precision = props.config.precision;
  if (precision !== void 0) {
    const current = draft.value;
    if (current !== void 0) {
      const rounded = applyRounding(current, precision, props.config.roundingMode ?? "round");
      if (rounded !== current) draft.value = rounded;
    }
  }
  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/number-field"
      :data-disabled="isDisabled ? 'true' : void 0"
    >
      <InputGroupNumberField
        :id="fieldId"
        :model-value="draft"
        :step="config.step"
        :step-snapping="config.step !== void 0"
        :min="minValue"
        :max="maxValue"
        :format-options="formatOptions"
        :disabled="isDisabled"
        :placeholder="placeholderText"
        input-class="text-left"
        @update:model-value="(v) => draft = v"
        @blur="onBlur"
      />
      <InputGroupAddon
        v-if="showClear"
        align="inline-end"
        class="[@media(hover:hover)]:opacity-0 transition-opacity group-hover/number-field:opacity-100 focus-within:opacity-100"
      >
        <InputGroupButton
          size="icon-xs"
          data-slot="number-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>
