<script setup>
import { computed, defineAsyncComponent } 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 { Markdown } from "../../../../ui/markdown";
import { useFieldValidation } from "../../../utils/validation";
import { useFormState } from "../../../utils/state";
defineOptions({ name: "ShwfedTableFieldRuntime" });
const ShwfedTable = defineAsyncComponent(() => import("../../../../table/index.vue"));
const props = defineProps({
  fieldId: { type: String, required: true },
  config: { type: null, required: true }
});
const { locale } = useI18n();
const formState = useFormState();
const inherited = injectCELContext();
const $cel = (expression, context) => _rawCel(expression, { ...celBindings(inherited), ...context });
const { isRequired, errors, warnings, visible } = useFieldValidation({
  fieldId: () => props.fieldId,
  config: () => props.config,
  $cel,
  locale: () => locale.value
});
const labelText = computed(() => getLocalizedText(props.config.label, locale.value));
const tooltipText = computed(
  () => props.config.tooltip ? getLocalizedText(props.config.tooltip, locale.value) : void 0
);
const tableConfig = computed(() => {
  const { dataSource: _omit, ...rest } = props.config.table;
  return rest;
});
const rowsModel = computed({
  get: () => {
    const binding = props.config.binding?.trim();
    if (!binding) return [];
    const v = formState.getAt(binding);
    return Array.isArray(v) ? v : [];
  },
  set: (next) => {
    const binding = props.config.binding?.trim();
    if (!binding) return;
    formState.setAtSilent(binding, next);
  }
});
</script>

<template>
  <Field orientation="vertical">
    <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>

    <ShwfedTable
      v-model:rows="rowsModel"
      :config="tableConfig"
    />
    <FieldMessages
      v-if="visible"
      :errors="errors"
      :warnings="warnings"
    />
  </Field>
</template>
