<script setup>
import { Field, FieldLabel } from "../../../../ui/field";
import { ExpressionEditor } from "../../../../ui/expression-editor";
import { Markdown } from "../../../../ui/markdown";
import { getStructFieldDescription, getStructFieldTitle } from "../../../schema";
import TriggersField from "../../../components/triggers-field.vue";
import { schema } from "./schema";
defineOptions({ name: "ShwfedStateWriteActionConfig" });
const value = defineModel({ type: null, ...{ required: true } });
const actionSchema = schema(() => {
});
const fieldTitle = (f) => getStructFieldTitle(actionSchema, f) ?? f;
const fieldDescription = (f) => getStructFieldDescription(actionSchema, f);
function updateTriggers(next) {
  const draft = { ...value.value };
  if (next.length === 0) Reflect.deleteProperty(draft, "onSuccess");
  else draft.onSuccess = next;
  value.value = draft;
}
</script>

<template>
  <div class="flex flex-col gap-3">
    <Field orientation="vertical">
      <FieldLabel class="text-xs text-zinc-500">
        <template
          v-if="fieldDescription('expression')"
          #tooltip
        >
          <Markdown
            :source="fieldDescription('expression')"
            block
            class="prose prose-sm prose-zinc"
          />
        </template>
        {{ fieldTitle("expression") }}
      </FieldLabel>
      <ExpressionEditor
        :model-value="value.expression"
        multiline
        placeholder="例：{ invoices: rows, totalAmount: rows.map(r, r.amount).sum() }"
        result-type="map"
        class="min-h-16"
        @update:model-value="(v) => value = { ...value, expression: v }"
      />
    </Field>

    <Field orientation="vertical">
      <FieldLabel class="text-xs text-zinc-500">
        <template
          v-if="fieldDescription('onSuccess')"
          #tooltip
        >
          <Markdown
            :source="fieldDescription('onSuccess')"
            block
            class="prose prose-sm prose-zinc"
          />
        </template>
        {{ fieldTitle("onSuccess") }}
      </FieldLabel>
      <TriggersField
        :triggers="value.onSuccess ?? []"
        @update:triggers="updateTriggers"
      />
    </Field>
  </div>
</template>
