<script setup>
import { Icon } from "@iconify/vue";
import { computed } from "vue";
import { Button } from "../../../../ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "../../../../ui/dropdown-menu";
import { ExpressionEditor } from "../../../../ui/expression-editor";
import DerivedValueEditor from "../../../DerivedValueEditor.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 { getStructFieldDescription, getStructFieldTitle } from "../../../schema";
import { DEFAULT_FIELD_ORIENTATION, FIELD_ORIENTATION_OPTIONS } from "../../../utils/common";
import { itemSchema, schema } from "./schema";
defineOptions({ name: "ShwfedComboboxSingleFieldConfig" });
const value = defineModel({ type: null, ...{ required: true } });
const fieldSchema = schema(() => {
});
const fieldTitle = (f) => getStructFieldTitle(fieldSchema, f) ?? f;
const fieldDescription = (f) => getStructFieldDescription(fieldSchema, f);
const itemFieldSchema = itemSchema(() => {
});
const itemFieldTitle = (f) => getStructFieldTitle(itemFieldSchema, f) ?? f;
const itemFieldDescription = (f) => getStructFieldDescription(itemFieldSchema, f);
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 items = computed(() => value.value.items ?? []);
function newId() {
  return typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    const r = Math.random() * 16 | 0;
    const v = c === "x" ? r : r & 3 | 8;
    return v.toString(16);
  });
}
function newItem() {
  return {
    id: newId(),
    label: [{ locale: "zh", message: "" }],
    value: { kind: "text", value: "" }
  };
}
function patchItem(index, patch) {
  const next = [...value.value.items ?? []];
  const cur = next[index];
  if (!cur) return;
  next[index] = { ...cur, ...patch };
  value.value = { ...value.value, items: next };
}
function addItem() {
  value.value = { ...value.value, items: [...value.value.items ?? [], newItem()] };
}
function removeItem(index) {
  const next = [...value.value.items ?? []];
  next.splice(index, 1);
  value.value = { ...value.value, items: next };
}
function setItemKind(index, kind) {
  const cur = value.value.items?.[index];
  if (!cur || cur.value.kind === kind) return;
  patchItem(index, {
    value: kind === "text" ? { kind: "text", value: "" } : { kind: "number", value: 0 }
  });
}
function setItemTextValue(index, text) {
  patchItem(index, { value: { kind: "text", value: text } });
}
function setItemNumberValue(index, n) {
  patchItem(index, {
    value: {
      kind: "number",
      value: typeof n === "number" && Number.isFinite(n) ? n : 0
    }
  });
}
function setItemLabel(index, label) {
  patchItem(index, { label });
}
function setItemTooltip(index, tooltip) {
  const isEmpty = !tooltip || tooltip.every((l) => l.message.trim().length === 0);
  if (isEmpty) {
    const cur = value.value.items?.[index];
    if (!cur) return;
    const { tooltip: _omit, ...rest } = cur;
    const next = [...value.value.items ?? []];
    next[index] = rest;
    value.value = { ...value.value, items: next };
  } else {
    patchItem(index, { tooltip });
  }
}
</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.role`"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("binding") }}
        </FieldLabel>
        <InputGroup>
          <InputGroupInput
            v-model="pathText"
            placeholder="例：user.role"
            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
          translate-hint="form field label"
          :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
          translate-hint="form field placeholder"
          :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
          translate-hint="form field tooltip"
          :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('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 #tooltip>
          <Markdown
            source="下拉框可选项列表"
            block
            class="prose prose-sm prose-zinc"
          />
        </template>
        {{ fieldTitle("items") }}
      </FieldLabel>

      <div class="flex flex-col gap-3">
        <div
          v-for="(item, index) in items"
          :key="item.id"
          data-slot="combobox-single-item"
          class="relative pt-8 grid grid-cols-3 gap-3 rounded border border-zinc-200 bg-zinc-50/40 p-3"
        >
          <InputGroupButton
            variant="destructive"
            size="icon-xs"
            data-slot="combobox-single-item-delete"
            aria-label="删除选项"
            class="absolute right-2 top-2 z-10"
            @click="removeItem(index)"
          >
            <Icon icon="fluent:delete-20-regular" />
          </InputGroupButton>

          <Field orientation="vertical">
            <FieldLabel class="text-xs text-zinc-500">
              <template
                v-if="itemFieldDescription('label')"
                #tooltip
              >
                <Markdown
                  :source="itemFieldDescription('label')"
                  block
                  class="prose prose-sm prose-zinc"
                />
              </template>
              {{ itemFieldTitle("label") }}
            </FieldLabel>
            <LocaleField
              markdown
              translate-hint="combobox option label"
              :model-value="item.label"
              @update:model-value="(v) => setItemLabel(index, v)"
            />
          </Field>

          <Field orientation="vertical">
            <FieldLabel class="text-xs text-zinc-500">
              <template
                v-if="itemFieldDescription('value')"
                #tooltip
              >
                <Markdown
                  :source="itemFieldDescription('value')"
                  block
                  class="prose prose-sm prose-zinc"
                />
              </template>
              {{ itemFieldTitle("value") }}
            </FieldLabel>
            <InputGroup>
              <InputGroupAddon align="inline-start">
                <DropdownMenu>
                  <DropdownMenuTrigger as-child>
                    <InputGroupButton
                      size="icon-sm"
                      as-child
                    >
                      <button
                        type="button"
                        data-slot="combobox-single-item-kind-trigger"
                        class="text-zinc-500 transition-colors hover:text-zinc-700 [&_svg:not([class*='size-'])]:size-3.5"
                        aria-label="切换值类型"
                      >
                        <Icon
                          :icon="item.value.kind === 'number' ? 'fluent:number-symbol-20-regular' : 'fluent:textbox-20-regular'"
                        />
                      </button>
                    </InputGroupButton>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="start">
                    <DropdownMenuItem @select="setItemKind(index, 'text')">
                      <Icon icon="fluent:textbox-20-regular" />
                      <span>文本</span>
                    </DropdownMenuItem>
                    <DropdownMenuItem @select="setItemKind(index, 'number')">
                      <Icon icon="fluent:number-symbol-20-regular" />
                      <span>数字</span>
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </InputGroupAddon>

              <InputGroupInput
                v-if="item.value.kind === 'text'"
                :model-value="item.value.value"
                placeholder="例：admin"
                @update:model-value="(v) => setItemTextValue(index, String(v ?? ''))"
              />
              <InputGroupNumberField
                v-else
                :model-value="item.value.value"
                @update:model-value="(v) => setItemNumberValue(index, v)"
              />
            </InputGroup>
          </Field>

          <Field orientation="vertical">
            <FieldLabel class="text-xs text-zinc-500">
              <template
                v-if="itemFieldDescription('tooltip')"
                #tooltip
              >
                <Markdown
                  :source="itemFieldDescription('tooltip')"
                  block
                  class="prose prose-sm prose-zinc"
                />
              </template>
              {{ itemFieldTitle("tooltip") }}
            </FieldLabel>
            <LocaleField
              markdown
              translate-hint="combobox option tooltip"
              :model-value="item.tooltip"
              @update:model-value="(v) => setItemTooltip(index, v)"
            />
          </Field>
        </div>

        <Button
          type="button"
          data-slot="combobox-single-add-item"
          class="w-full justify-center"
          @click="addItem"
        >
          <Icon icon="fluent:add-20-regular" />
          <span>增加选项</span>
        </Button>
      </div>
    </Field>

    <div class="grid grid-cols-3 gap-3">
      <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\u4E0B\u62C9\u6846\u4ECD\u7136\u6E32\u67D3\u4F46\u4E0D\u53EF\u9009\u62E9'"
              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\u9009\u9879\u7684\u6807\u7B7E'"
              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.category"
        @update:model-value="(v) => value = { ...value, derived: v }"
      />
    </Field>
  </div>
</template>
