<script setup>
import { format as formatDate } from "date-fns";
import { Effect } from "effect";
import { computed, ref } 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 { DatePicker, DATE_PICKER_DEFAULT_FORMATS } from "../../../../ui/date-picker";
import { Field, FieldLabel, FieldMessages } from "../../../../ui/field";
import { Markdown } from "../../../../ui/markdown";
import { DEFAULT_FIELD_ORIENTATION } from "../../../utils/common";
import { useFieldValidation } from "../../../utils/validation";
import { useFormReadonly } from "../../../utils/readonly";
import { useFormState } from "../../../utils/state";
defineOptions({ name: "ShwfedDateFieldRuntime" });
const props = defineProps({
  fieldId: { type: String, required: true },
  config: { type: null, required: true }
});
const { locale } = useI18n();
const { state, getAt, setAt } = 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 resolvedValueFormat = computed(
  () => props.config.valueFormat ?? DATE_PICKER_DEFAULT_FORMATS.date.value
);
const shortcuts = computed(() => {
  const list = props.config.presets;
  if (!list || list.length === 0) return void 0;
  return list.map((preset) => ({
    name: preset.label,
    value: () => {
      try {
        const d = Effect.runSync($cel(preset.value, { form: state.value ?? {} }));
        return formatDate(d, resolvedValueFormat.value);
      } catch (err) {
        console.error(`[shwfed-form] failed to evaluate preset "${preset.value}" for ${props.fieldId}:`, err);
        return "";
      }
    }
  }));
});
const uncontrolled = ref(void 0);
const model = computed({
  get: () => {
    const path = props.config.binding;
    if (path == null) return uncontrolled.value;
    const raw = getAt(path);
    return typeof raw === "string" && raw.length > 0 ? raw : void 0;
  },
  set: (next) => {
    const path = props.config.binding;
    if (path == null) {
      uncontrolled.value = next;
      return;
    }
    setAt(path, next);
  }
});
const { isRequired, errors, warnings, visible } = useFieldValidation({
  fieldId: () => props.fieldId,
  config: () => props.config,
  $cel,
  locale: () => locale.value
});
</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"
    >
      {{ model || "\u2014" }}
    </div>
    <DatePicker
      v-else
      :id="fieldId"
      v-model="model"
      type="date"
      :format="config.format"
      :value-format="config.valueFormat"
      :placeholder="placeholderText"
      :disabled="isDisabled"
      :shortcuts="shortcuts"
    />
    <FieldMessages
      v-if="visible"
      :errors="errors"
      :warnings="warnings"
    />
  </Field>
</template>
