<script setup>
import AdminLayout from "@/Layouts/AdminLayout.vue";
import { useForm } from "@inertiajs/vue3";
import { ref, watch } from "vue";

const props = defineProps({ settings: Object, defaults: Object });
const form = useForm({
  file_name_pattern: props.settings.file_name_pattern || props.defaults.file_name_pattern,
  date_format: props.settings.date_format || props.defaults.date_format,
  unresolved_policy: props.settings.unresolved_policy || props.defaults.unresolved_policy,
  preview_enabled: props.settings.preview_enabled ? 1 : 0,
  whitelist: JSON.stringify(props.settings.whitelist || {}, null, 2),
  date_formats: JSON.stringify(props.settings.date_formats || {}, null, 2),
});

const whitelistError = ref(null);
const dateFormatsError = ref(null);

function validateJson(source, targetError, expectations = "object") {
  try {
    const parsed = JSON.parse(source.value);
    if (
      expectations === "object" &&
      (parsed === null || Array.isArray(parsed) || typeof parsed !== "object")
    ) {
      targetError.value = "Mora biti JSON objekt";
    } else {
      targetError.value = null;
    }
  } catch (e) {
    targetError.value = "Neveljaven JSON";
  }
}

watch(
  () => form.whitelist,
  () => validateJson({ value: form.whitelist }, whitelistError)
);
watch(
  () => form.date_formats,
  () => validateJson({ value: form.date_formats }, dateFormatsError)
);

function submit() {
  if (whitelistError.value || dateFormatsError.value) {
    return;
  }
  let wl = null;
  try {
    wl = JSON.parse(form.whitelist);
  } catch (e) {
    wl = null;
  }
  let df = null;
  try {
    df = JSON.parse(form.date_formats);
  } catch (e) {
    df = null;
  }
  form
    .transform((d) => ({
      ...d,
      preview_enabled: !!d.preview_enabled,
      whitelist: wl,
      date_formats: df,
    }))
    .put(route("admin.document-settings.update"));
}
</script>

<template>
  <AdminLayout title="Nastavitve dokumentov">
    <div class="max-w-3xl mx-auto space-y-6">
      <h1 class="text-2xl font-semibold">Nastavitve dokumentov</h1>
      <form @submit.prevent="submit" class="space-y-6 bg-white p-6 border rounded">
        <div class="grid md:grid-cols-2 gap-4">
          <label class="flex flex-col gap-1">
            <span class="text-sm font-medium">Vzorec imena</span>
            <input v-model="form.file_name_pattern" class="border rounded px-3 py-2" />
            <span class="text-xs text-gray-500"
              >Podprti placeholderji: {slug} {version} {generation.date}
              {generation.timestamp}</span
            >
            <span v-if="form.errors.file_name_pattern" class="text-xs text-rose-600">{{
              form.errors.file_name_pattern
            }}</span>
          </label>
          <label class="flex flex-col gap-1">
            <span class="text-sm font-medium">Privzeti datum format</span>
            <input v-model="form.date_format" class="border rounded px-3 py-2" />
            <span class="text-xs text-gray-500">npr. Y-m-d ali d.m.Y</span>
            <span v-if="form.errors.date_format" class="text-xs text-rose-600">{{
              form.errors.date_format
            }}</span>
          </label>
          <label class="flex flex-col gap-1">
            <span class="text-sm font-medium">Politika nerešenih</span>
            <select v-model="form.unresolved_policy" class="border rounded px-3 py-2">
              <option value="fail">Fail</option>
              <option value="blank">Blank</option>
              <option value="keep">Keep</option>
            </select>
            <span v-if="form.errors.unresolved_policy" class="text-xs text-rose-600">{{
              form.errors.unresolved_policy
            }}</span>
          </label>
          <label class="flex items-center gap-2 mt-6">
            <input
              type="checkbox"
              v-model="form.preview_enabled"
              true-value="1"
              false-value="0"
            />
            <span class="text-sm font-medium">Omogoči predoglede</span>
          </label>
        </div>
        <div class="grid md:grid-cols-2 gap-6">
          <label class="flex flex-col gap-1">
            <span class="text-sm font-medium">Whitelist (JSON)</span>
            <textarea
              v-model="form.whitelist"
              rows="8"
              class="font-mono text-xs border rounded p-2"
            ></textarea>
            <span v-if="whitelistError" class="text-xs text-rose-600">{{
              whitelistError
            }}</span>
            <span v-else-if="form.errors.whitelist" class="text-xs text-rose-600">{{
              form.errors.whitelist
            }}</span>
          </label>
          <label class="flex flex-col gap-1">
            <span class="text-sm font-medium">Date formats override (JSON)</span>
            <textarea
              v-model="form.date_formats"
              rows="8"
              class="font-mono text-xs border rounded p-2"
            ></textarea>
            <span class="text-xs text-gray-500"
              >Primer: {"contract.start_date":"d.m.Y"}</span
            >
            <span v-if="dateFormatsError" class="text-xs text-rose-600">{{
              dateFormatsError
            }}</span>
          </label>
        </div>
        <div class="flex items-center gap-3">
          <button
            :disabled="form.processing"
            class="px-4 py-2 bg-indigo-600 text-white rounded disabled:opacity-50"
          >
            {{ form.processing ? "Shranjevanje..." : "Shrani" }}
          </button>
          <span v-if="form.wasSuccessful" class="text-sm text-emerald-600"
            >Shranjeno</span
          >
        </div>
      </form>
    </div>
  </AdminLayout>
</template>
