<template>
  <UForm
    ref="formRef"
    :schema="schema"
    :class="ui.root({ class: [props.ui?.root, props.class] })"
    :validate-on="['input']"
    nested
  >
    <UFormField
      :label="label"
      :name="titleKey"
    >
      <UInput
        v-model="title"
        v-bind="inputProps"
        class="w-full"
      />
    </UFormField>
    <UFormField :name="slugKey" class="-mt-3" eager-validation>
      <UInput
        v-model="slug"
        class="w-full"
        size="xs"
        variant="none"
        :placeholder="isRegenerate ? '\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A' : '\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0441\u043B\u0430\u0433'"
        :disabled="isRegenerate"
        :ui="{
  base: 'text-muted'
}"
      >
        <template #leading>
          <UButton
            size="xs"
            variant="link"
            :icon="appConfig.ui.icons.link"
            class="p-0"
            :color="isRegenerate ? 'success' : 'neutral'"
            @click="isRegenerate = !isRegenerate"
          />
        </template>
      </UInput>
    </UFormField>
  </UForm>
</template>

<script>
import theme from "#build/cms/form-slug";
import { useAppConfig } from "#imports";
import { computed, ref, useTemplateRef, watch } from "vue";
import { z } from "zod";
import { tv } from "../tv";
import { slugify } from "../utils/slugify";
</script>

<script setup>
const props = defineProps({
  name: { type: String, required: false, default: "slug" },
  regenerate: { type: Boolean, required: false },
  label: { type: String, required: false },
  titleKey: { type: String, required: false, default: "title" },
  slugKey: { type: String, required: false, default: "slug" },
  inputProps: { type: Object, required: false },
  class: { type: null, required: false },
  ui: { type: null, required: false }
});
const title = defineModel("title", { type: String });
const slug = defineModel("slug", { type: String });
const appConfig = useAppConfig();
const schema = z.object({
  title: z.string().min(1),
  slug: z.string().min(1)
});
const formRef = useTemplateRef("formRef");
const isRegenerate = ref(props.regenerate);
watch(title, () => {
  if (!isRegenerate.value) {
    return;
  }
  slug.value = slugify(title.value);
});
watch(slug, () => {
  if (formRef.value?.getErrors("slug")) {
    formRef.value?.clear("slug");
  }
});
const ui = computed(() => tv({ extend: tv(theme), ...appConfig.cms?.formSlug || {} })());
</script>
