<script setup>
import { computed } from "vue";
import { Icon } from "@iconify/vue";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger
} from "../../../../ui/dropdown-menu";
import { ExpressionEditor } from "../../../../ui/expression-editor";
import DerivedValueEditor from "../../../DerivedValueEditor.vue";
import ValidationRulesField from "../../../ValidationRulesField.vue";
import { Field, FieldLabel } from "../../../../ui/field";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
  InputGroupInput,
  InputGroupNumberField
} from "../../../../ui/input-group";
import { Locale as LocaleField } from "../../../../ui/locale";
import { Markdown } from "../../../../ui/markdown";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "../../../../ui/select";
import { Switch } from "../../../../ui/switch";
import { getStructFieldDescription, getStructFieldTitle } from "../../../schema";
import { DEFAULT_FIELD_ORIENTATION, FIELD_ORIENTATION_OPTIONS } from "../../../utils/common";
import { schema } from "./schema";
defineOptions({ name: "ShwfedNumberFieldConfig" });
const value = defineModel({ type: null, ...{ required: true } });
const fieldSchema = schema(() => {
});
const fieldTitle = (f) => getStructFieldTitle(fieldSchema, f) ?? f;
const fieldDescription = (f) => getStructFieldDescription(fieldSchema, f);
const ROUNDING_MODE_OPTIONS = [
  { value: "round", label: "\u56DB\u820D\u4E94\u5165" },
  { value: "floor", label: "\u5411\u4E0B\u53D6\u6574" },
  { value: "ceil", label: "\u5411\u4E0A\u53D6\u6574" }
];
const pathText = computed({
  get: () => value.value.binding ?? "",
  set: (next) => {
    const trimmed = next.trim();
    if (trimmed.length === 0) {
      const { binding: _omit, ...rest } = value.value;
      value.value = rest;
    } else {
      value.value = { ...value.value, binding: trimmed };
    }
  }
});
const currentRoundingModeLabel = computed(
  () => ROUNDING_MODE_OPTIONS.find((o) => o.value === (value.value.roundingMode ?? "round"))?.label
);
function onPrecisionChange(v) {
  if (v === void 0) {
    const { precision: _p, roundingMode: _r, ...rest } = value.value;
    value.value = rest;
  } else if (value.value.roundingMode === void 0) {
    value.value = { ...value.value, precision: v, roundingMode: "round" };
  } else {
    value.value = { ...value.value, precision: v };
  }
}
function onRoundingModeChange(mode) {
  value.value = { ...value.value, roundingMode: mode };
}
function onStepChange(v) {
  if (v === void 0 || !(v > 0)) {
    const { step: _omit, ...rest } = value.value;
    value.value = rest;
  } else {
    value.value = { ...value.value, step: v };
  }
}
function onValueAsStringChange(next) {
  if (next) {
    value.value = { ...value.value, valueAsString: true };
  } else {
    const { valueAsString: _omit, ...rest } = value.value;
    value.value = rest;
  }
}
</script>

<template>
  <div class="flex flex-col gap-3">
    <div class="grid grid-cols-2 gap-3">
      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('displayName')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('displayName')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("displayName") }}
        </FieldLabel>
        <InputGroup>
          <InputGroupInput
            :model-value="value.displayName ?? ''"
            placeholder="例：年龄"
            @update:model-value="(v) => {
  const s = String(v ?? '');
  value = { ...value, displayName: s.length > 0 ? s : void 0 };
}"
          />
        </InputGroup>
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              source="写入表单状态的嵌套键路径，使用 `.` 分隔，例如 `user.age`"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("binding") }}
        </FieldLabel>
        <InputGroup>
          <InputGroupInput
            v-model="pathText"
            placeholder="例：user.age"
            class="font-mono"
          />
        </InputGroup>
      </Field>
    </div>

    <div class="grid grid-cols-3 gap-3">
      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('label')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('label')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("label") }}
        </FieldLabel>
        <LocaleField
          :model-value="value.label"
          @update:model-value="(v) => value = { ...value, label: v }"
        />
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('placeholder')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('placeholder')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("placeholder") }}
        </FieldLabel>
        <LocaleField
          :model-value="value.placeholder"
          @update:model-value="(v) => value = { ...value, placeholder: v }"
        />
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('tooltip')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('tooltip')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("tooltip") }}
        </FieldLabel>
        <LocaleField
          markdown
          :model-value="value.tooltip"
          @update:model-value="(v) => value = { ...value, tooltip: v }"
        />
      </Field>
    </div>

    <div class="grid grid-cols-3 gap-3">
      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('precision')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('precision')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("precision") }}
        </FieldLabel>
        <InputGroup>
          <InputGroupNumberField
            :model-value="value.precision"
            :min="0"
            @update:model-value="onPrecisionChange"
          />
          <InputGroupAddon
            v-if="value.precision !== void 0"
            align="inline-end"
          >
            <DropdownMenu>
              <DropdownMenuTrigger as-child>
                <InputGroupButton
                  variant="ghost"
                  class="pr-1.5! text-xs"
                >
                  {{ currentRoundingModeLabel }}
                  <Icon
                    icon="lucide:chevron-down"
                    class="size-3"
                  />
                </InputGroupButton>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem
                  v-for="opt in ROUNDING_MODE_OPTIONS"
                  :key="opt.value"
                  @select="onRoundingModeChange(opt.value)"
                >
                  {{ opt.label }}
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </InputGroupAddon>
        </InputGroup>
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('step')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('step')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("step") }}
        </FieldLabel>
        <InputGroup>
          <InputGroupNumberField
            :model-value="value.step"
            :min="0"
            @update:model-value="onStepChange"
          />
        </InputGroup>
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('orientation')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('orientation')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("orientation") }}
        </FieldLabel>
        <Select
          :model-value="value.orientation ?? DEFAULT_FIELD_ORIENTATION"
          @update:model-value="(v) => value = { ...value, orientation: v }"
        >
          <SelectTrigger class="w-full">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem
              v-for="opt in FIELD_ORIENTATION_OPTIONS"
              :key="opt.value"
              :value="opt.value"
            >
              {{ opt.label }}
            </SelectItem>
          </SelectContent>
        </Select>
      </Field>
    </div>

    <Field orientation="vertical">
      <FieldLabel class="text-xs text-zinc-500">
        <template
          v-if="fieldDescription('valueAsString')"
          #tooltip
        >
          <Markdown
            :source="fieldDescription('valueAsString')"
            block
            class="prose prose-sm prose-zinc"
          />
        </template>
        {{ fieldTitle("valueAsString") }}
      </FieldLabel>
      <div>
        <Switch
          :model-value="value.valueAsString ?? false"
          @update:model-value="onValueAsStringChange"
        />
      </div>
    </Field>

    <div class="grid grid-cols-2 gap-3">
      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              :source="fieldDescription('min') ?? '\u5141\u8BB8\u8F93\u5165\u7684\u6700\u5C0F\u503C\u8868\u8FBE\u5F0F'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("min") }}
        </FieldLabel>
        <ExpressionEditor
          :model-value="value.min ?? ''"
          placeholder="例：0"
          result-type="number"
          class="min-h-10"
          @update:model-value="(v) => value = { ...value, min: v.length > 0 ? v : void 0 }"
        />
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              :source="fieldDescription('max') ?? '\u5141\u8BB8\u8F93\u5165\u7684\u6700\u5927\u503C\u8868\u8FBE\u5F0F'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("max") }}
        </FieldLabel>
        <ExpressionEditor
          :model-value="value.max ?? ''"
          placeholder="例：100"
          result-type="number"
          class="min-h-10"
          @update:model-value="(v) => value = { ...value, max: v.length > 0 ? v : void 0 }"
        />
      </Field>
    </div>

    <div class="grid grid-cols-3 gap-3">
      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              :source="fieldDescription('required') ?? '\u8FD4\u56DE `true` \u65F6\u663E\u793A\u5FC5\u586B\u661F\u53F7\u5E76\u8981\u6C42\u975E\u7A7A'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("required") }}
        </FieldLabel>
        <ExpressionEditor
          :model-value="value.required ?? ''"
          placeholder="例：form.type == 'company'"
          result-type="bool"
          class="min-h-10"
          @update:model-value="(v) => value = { ...value, required: v.length > 0 ? v : void 0 }"
        />
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              :source="fieldDescription('hidden') ?? '\u8FD4\u56DE `true` \u65F6\u5B57\u6BB5\u5728\u6240\u6709\u5E03\u5C40\u4E2D\u90FD\u4E0D\u6E32\u67D3'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("hidden") }}
        </FieldLabel>
        <ExpressionEditor
          :model-value="value.hidden ?? ''"
          placeholder="例：form.role == 'guest'"
          result-type="bool"
          class="min-h-10"
          @update:model-value="(v) => value = { ...value, hidden: v.length > 0 ? v : void 0 }"
        />
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              :source="fieldDescription('disabled') ?? '\u8FD4\u56DE `true` \u65F6\u8F93\u5165\u6846\u4ECD\u7136\u6E32\u67D3\u4F46\u4E0D\u53EF\u7F16\u8F91'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("disabled") }}
        </FieldLabel>
        <ExpressionEditor
          :model-value="value.disabled ?? ''"
          placeholder="例：form.status == 'locked'"
          result-type="bool"
          class="min-h-10"
          @update:model-value="(v) => value = { ...value, disabled: v.length > 0 ? v : void 0 }"
        />
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              :source="fieldDescription('readonly') ?? '\u8FD4\u56DE `true` \u65F6\u4EC5\u4EE5\u7EAF\u6587\u672C\u5C55\u793A\u5F53\u524D\u503C'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("readonly") }}
        </FieldLabel>
        <ExpressionEditor
          :model-value="value.readonly ?? ''"
          placeholder="例：form.id != null"
          result-type="bool"
          class="min-h-10"
          @update:model-value="(v) => value = { ...value, readonly: v.length > 0 ? v : void 0 }"
        />
      </Field>
    </div>

    <Field orientation="vertical">
      <FieldLabel class="text-xs text-zinc-500">
        <template #tooltip>
          <Markdown
            :source="fieldDescription('derived')"
            block
            class="prose prose-sm prose-zinc"
          />
        </template>
        {{ fieldTitle("derived") }}
      </FieldLabel>
      <DerivedValueEditor
        :model-value="value.derived"
        result-type="number"
        placeholder="例：form.price * form.qty"
        @update:model-value="(v) => value = { ...value, derived: v }"
      />
    </Field>

    <Field orientation="vertical">
      <FieldLabel class="text-xs text-zinc-500">
        <template #tooltip>
          <Markdown
            :source="fieldDescription('validations')"
            block
            class="prose prose-sm prose-zinc"
          />
        </template>
        {{ fieldTitle("validations") }}
      </FieldLabel>
      <ValidationRulesField
        :model-value="value.validations"
        @update:model-value="(v) => value = { ...value, validations: v.length > 0 ? v : void 0 }"
      />
    </Field>
  </div>
</template>
