<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 { IconPicker } from "../../../../ui/icon-picker";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
  InputGroupInput,
  InputGroupNumberField,
  InputGroupText
} 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: "ShwfedNumberRangeFieldConfig" });
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 bindingMode = computed(
  () => Array.isArray(value.value.binding) ? "split" : "single"
);
const singlePathText = computed({
  get: () => typeof value.value.binding === "string" ? 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 splitStartText = computed(
  () => Array.isArray(value.value.binding) ? value.value.binding[0] : ""
);
const splitEndText = computed(
  () => Array.isArray(value.value.binding) ? value.value.binding[1] : ""
);
function setSplitStart(next) {
  const cur = Array.isArray(value.value.binding) ? value.value.binding : ["", ""];
  value.value = { ...value.value, binding: [next.trim(), cur[1]] };
}
function setSplitEnd(next) {
  const cur = Array.isArray(value.value.binding) ? value.value.binding : ["", ""];
  value.value = { ...value.value, binding: [cur[0], next.trim()] };
}
function toggleBindingMode() {
  if (bindingMode.value === "single") {
    value.value = { ...value.value, binding: ["", ""] };
  } else {
    const { binding: _omit, ...rest } = value.value;
    value.value = rest;
  }
}
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 setSeparatorIcon(next) {
  const trimmed = next.trim();
  if (trimmed.length === 0) {
    const { rangeSeparatorIcon: _omit, ...rest } = value.value;
    value.value = rest;
  } else {
    value.value = { ...value.value, rangeSeparatorIcon: trimmed };
  }
}
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="写入表单状态的嵌套键路径，使用 `.` 分隔。单路径模式写入 `[start, end]` 数值数组；拆分模式分别写入起始与结束两端"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("binding") }}
        </FieldLabel>
        <template v-if="bindingMode === 'single'">
          <InputGroup>
            <InputGroupInput
              v-model="singlePathText"
              placeholder="例：score.range"
              class="font-mono"
            />
            <InputGroupAddon align="inline-end">
              <InputGroupButton
                size="icon-xs"
                aria-label="拆分起止绑定路径"
                @click="toggleBindingMode"
              >
                <Icon icon="fluent:split-horizontal-20-regular" />
              </InputGroupButton>
            </InputGroupAddon>
          </InputGroup>
        </template>
        <template v-else>
          <div class="grid grid-cols-2 gap-2">
            <InputGroup>
              <InputGroupAddon align="inline-start">
                <InputGroupText class="text-xs text-zinc-400">
                  起
                </InputGroupText>
              </InputGroupAddon>
              <InputGroupInput
                :model-value="splitStartText"
                placeholder="例：score.start"
                class="font-mono"
                @update:model-value="(v) => setSplitStart(String(v ?? ''))"
              />
            </InputGroup>
            <InputGroup>
              <InputGroupAddon align="inline-start">
                <InputGroupText class="text-xs text-zinc-400">
                  止
                </InputGroupText>
              </InputGroupAddon>
              <InputGroupInput
                :model-value="splitEndText"
                placeholder="例：score.end"
                class="font-mono"
                @update:model-value="(v) => setSplitEnd(String(v ?? ''))"
              />
              <InputGroupAddon align="inline-end">
                <InputGroupButton
                  size="icon-xs"
                  aria-label="合并起止绑定路径"
                  @click="toggleBindingMode"
                >
                  <Icon icon="fluent:merge-vertical-20-regular" />
                </InputGroupButton>
              </InputGroupAddon>
            </InputGroup>
          </div>
        </template>
      </Field>
    </div>

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

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

    <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-2 gap-3">
      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              :source="fieldDescription('rangeSeparatorIcon') ?? '\u8303\u56F4\u4E24\u7AEF\u4E4B\u95F4\u5206\u9694\u56FE\u6807\u7684 Iconify \u540D\u79F0'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("rangeSeparatorIcon") }}
        </FieldLabel>
        <IconPicker
          :model-value="value.rangeSeparatorIcon ?? ''"
          placeholder="例：lucide:arrow-right"
          @update:model-value="setSeparatorIcon"
        />
      </Field>

      <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>

    <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="dyn"
        placeholder="例：[form.lo, form.hi]"
        @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>
