<script setup>
import { Icon } from "@iconify/vue";
import { computed } from "vue";
import { format as formatDate } from "date-fns";
import { Button } from "../../../../ui/button";
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, 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 { getStructFieldDescription, getStructFieldTitle } from "../../../schema";
import { DEFAULT_FIELD_ORIENTATION, FIELD_ORIENTATION_OPTIONS } from "../../../utils/common";
import { HOUR_CYCLE_OPTIONS, presetSchema, schema, TIME_GRANULARITY_OPTIONS } from "./schema";
defineOptions({ name: "ShwfedDateTimeFieldConfig" });
const value = defineModel({ type: null, ...{ required: true } });
const fieldSchema = schema(() => {
});
const fieldTitle = (f) => getStructFieldTitle(fieldSchema, f) ?? f;
const fieldDescription = (f) => getStructFieldDescription(fieldSchema, f);
const presetFieldSchema = presetSchema(() => {
});
const presetFieldTitle = (f) => getStructFieldTitle(presetFieldSchema, f) ?? f;
const presetFieldDescription = (f) => getStructFieldDescription(presetFieldSchema, f);
const presets = computed(() => value.value.presets ?? []);
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 newPreset() {
  return {
    id: newId(),
    label: [{ locale: "zh", message: "" }],
    value: ""
  };
}
function patchPreset(index, patch) {
  const next = [...value.value.presets ?? []];
  const cur = next[index];
  if (!cur) return;
  next[index] = { ...cur, ...patch };
  value.value = { ...value.value, presets: next };
}
function addPreset() {
  value.value = { ...value.value, presets: [...value.value.presets ?? [], newPreset()] };
}
function removePreset(index) {
  const next = [...value.value.presets ?? []];
  next.splice(index, 1);
  value.value = { ...value.value, presets: next };
}
function setPresetLabel(index, label) {
  patchPreset(index, { label });
}
function setPresetValue(index, expr) {
  patchPreset(index, { value: expr });
}
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 formatText = computed({
  get: () => value.value.format ?? "",
  set: (next) => {
    const trimmed = next.trim();
    if (trimmed.length === 0) {
      const { format: _omit, ...rest } = value.value;
      value.value = rest;
    } else {
      value.value = { ...value.value, format: trimmed };
    }
  }
});
const valueFormatText = computed({
  get: () => value.value.valueFormat ?? "",
  set: (next) => {
    const trimmed = next.trim();
    if (trimmed.length === 0) {
      const { valueFormat: _omit, ...rest } = value.value;
      value.value = rest;
    } else {
      value.value = { ...value.value, valueFormat: trimmed };
    }
  }
});
const timeGranularity = computed({
  get: () => value.value.timeGranularity ?? "second",
  set: (next) => {
    if (next === "second") {
      const { timeGranularity: _omit, ...rest } = value.value;
      value.value = rest;
    } else {
      value.value = { ...value.value, timeGranularity: next };
    }
  }
});
const hourCycle = computed({
  get: () => value.value.hourCycle ?? 24,
  set: (next) => {
    if (next === 24) {
      const { hourCycle: _omit, ...rest } = value.value;
      value.value = rest;
    } else {
      value.value = { ...value.value, hourCycle: next };
    }
  }
});
function previewFormat(fmt) {
  if (!fmt) return "";
  try {
    return formatDate(/* @__PURE__ */ new Date(), fmt);
  } catch {
    return "(\u65E0\u6548\u683C\u5F0F)";
  }
}
const formatExample = computed(() => previewFormat(value.value.format ?? ""));
const valueFormatExample = computed(() => previewFormat(value.value.valueFormat ?? ""));
</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="写入表单状态的嵌套键路径，使用 `.` 分隔，例如 `event.startAt`"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("binding") }}
        </FieldLabel>
        <InputGroup>
          <InputGroupInput
            v-model="pathText"
            placeholder="例：event.startAt"
            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 #tooltip>
            <Markdown
              :source="fieldDescription('format') ?? '\u8F93\u5165\u6846\u4E2D\u5C55\u793A\u65E5\u671F\u65F6\u95F4\u7684 `date-fns` \u683C\u5F0F\u4E32'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("format") }}
        </FieldLabel>
        <InputGroup>
          <InputGroupInput
            v-model="formatText"
            placeholder="例：yyyy-MM-dd HH:mm:ss"
            class="font-mono"
          />
          <InputGroupAddon
            v-if="formatExample"
            align="inline-end"
          >
            <InputGroupText class="text-xs text-zinc-400">
              {{ formatExample }}
            </InputGroupText>
          </InputGroupAddon>
        </InputGroup>
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              :source="fieldDescription('valueFormat') ?? '\u5199\u5165\u8868\u5355\u72B6\u6001\u7684 `date-fns` \u683C\u5F0F\u4E32'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("valueFormat") }}
        </FieldLabel>
        <InputGroup>
          <InputGroupInput
            v-model="valueFormatText"
            placeholder="例：yyyy-MM-dd HH:mm:ss"
            class="font-mono"
          />
          <InputGroupAddon
            v-if="valueFormatExample"
            align="inline-end"
          >
            <InputGroupText class="text-xs text-zinc-400">
              {{ valueFormatExample }}
            </InputGroupText>
          </InputGroupAddon>
        </InputGroup>
      </Field>
    </div>

    <Field orientation="vertical">
      <FieldLabel class="text-xs text-zinc-500">
        <template
          v-if="fieldDescription('presets')"
          #tooltip
        >
          <Markdown
            :source="fieldDescription('presets')"
            block
            class="prose prose-sm prose-zinc"
          />
        </template>
        {{ fieldTitle("presets") }}
      </FieldLabel>

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

          <Field orientation="vertical">
            <FieldLabel class="text-xs text-zinc-500">
              <template
                v-if="presetFieldDescription('label')"
                #tooltip
              >
                <Markdown
                  :source="presetFieldDescription('label')"
                  block
                  class="prose prose-sm prose-zinc"
                />
              </template>
              {{ presetFieldTitle("label") }}
            </FieldLabel>
            <LocaleField
              translate-hint="datetime field preset label"
              :model-value="preset.label"
              @update:model-value="(v) => setPresetLabel(index, v)"
            />
          </Field>

          <Field orientation="vertical">
            <FieldLabel class="text-xs text-zinc-500">
              <template
                v-if="presetFieldDescription('value')"
                #tooltip
              >
                <Markdown
                  :source="presetFieldDescription('value')"
                  block
                  class="prose prose-sm prose-zinc"
                />
              </template>
              {{ presetFieldTitle("value") }}
            </FieldLabel>
            <ExpressionEditor
              :model-value="preset.value"
              placeholder="例：now.offset(-1, &quot;hours&quot;)"
              result-type="Date"
              class="min-h-10"
              @update:model-value="(v) => setPresetValue(index, v)"
            />
          </Field>
        </div>

        <Button
          type="button"
          data-slot="datetime-field-add-preset"
          class="w-full justify-center"
          @click="addPreset"
        >
          <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
            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>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              :source="fieldDescription('timeGranularity') ?? '\u53EF\u7F16\u8F91\u5230\u7684\u6700\u5C0F\u65F6\u95F4\u5355\u4F4D'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("timeGranularity") }}
        </FieldLabel>
        <Select
          :model-value="timeGranularity"
          @update:model-value="(v) => timeGranularity = v"
        >
          <SelectTrigger class="w-full">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem
              v-for="opt in TIME_GRANULARITY_OPTIONS"
              :key="opt.value"
              :value="opt.value"
            >
              {{ opt.label }}
            </SelectItem>
          </SelectContent>
        </Select>
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              :source="fieldDescription('hourCycle') ?? '12 \u5C0F\u65F6\u5236\u6216 24 \u5C0F\u65F6\u5236'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("hourCycle") }}
        </FieldLabel>
        <Select
          :model-value="String(hourCycle)"
          @update:model-value="(v) => hourCycle = Number(v)"
        >
          <SelectTrigger class="w-full">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem
              v-for="opt in HOUR_CYCLE_OPTIONS"
              :key="opt.value"
              :value="String(opt.value)"
            >
              {{ opt.label }}
            </SelectItem>
          </SelectContent>
        </Select>
      </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="string"
        placeholder="例：form.createdAt"
        @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>
