<script setup>
// flowbite-vue table imports removed; using DataTableClient
import { EditIcon, TrashBinIcon, DottedMenu } from "@/Utilities/Icons";
import DialogModal from "@/Components/DialogModal.vue";
import ConfirmationModal from "@/Components/ConfirmationModal.vue";
import { computed, onMounted, ref, watch, nextTick } from "vue";
import { router, useForm } from "@inertiajs/vue3";
import InputLabel from "@/Components/InputLabel.vue";
import TextInput from "@/Components/TextInput.vue";
import Multiselect from "vue-multiselect";
import PrimaryButton from "@/Components/PrimaryButton.vue";
import ActionMessage from "@/Components/ActionMessage.vue";
import DataTableClient from "@/Components/DataTable/DataTableClient.vue";
import InlineColorPicker from "@/Components/InlineColorPicker.vue";
import Dropdown from "@/Components/Dropdown.vue";

const props = defineProps({
  decisions: Array,
  actions: Array,
  emailTemplates: { type: Array, default: () => [] },
  availableEvents: { type: Array, default: () => [] },
  segments: { type: Array, default: () => [] },
  archiveSettings: { type: Array, default: () => [] },
});

const drawerEdit = ref(false);
const drawerCreate = ref(false);
const showDelete = ref(false);
const toDelete = ref(null);

const search = ref("");
const selectedTemplateId = ref(null);
const onlyAutoMail = ref(false);

const actionOptions = ref([]);

// DataTable state
const sort = ref({ key: null, direction: null });
const page = ref(1);
const pageSize = ref(25);
const columns = [
  { key: "id", label: "#", sortable: true, class: "w-16" },
  { key: "name", label: "Ime", sortable: true },
  { key: "color_tag", label: "Barva", sortable: false },
  { key: "events", label: "Dogodki", sortable: false, class: "w-40" },
  { key: "belongs", label: "Pripada akcijam", sortable: false, class: "w-40" },
  { key: "auto_mail", label: "Auto mail", sortable: false, class: "w-46" },
];

const form = useForm({
  id: 0,
  name: "",
  color_tag: "",
  actions: [],
  auto_mail: false,
  email_template_id: null,
  events: [],
});

const createForm = useForm({
  name: "",
  color_tag: "",
  actions: [],
  auto_mail: false,
  email_template_id: null,
  events: [],
});

// When auto mail is disabled, also detach email template selection (edit form)
watch(
  () => form.auto_mail,
  (enabled) => {
    if (!enabled) {
      form.email_template_id = null;
    }
  }
);

// Same behavior for create form for consistency
watch(
  () => createForm.auto_mail,
  (enabled) => {
    if (!enabled) {
      createForm.email_template_id = null;
    }
  }
);

const openEditDrawer = (item) => {
  form.actions = [];
  form.id = item.id;
  form.name = item.name;
  form.color_tag = item.color_tag;
  form.auto_mail = !!item.auto_mail;
  form.email_template_id = item.email_template_id || null;
  form.events = (item.events || []).map((ev) => {
    let cfgObj = {};
    const pCfg = ev.pivot?.config;
    if (typeof pCfg === "string" && pCfg.trim() !== "") {
      try {
        cfgObj = JSON.parse(pCfg);
      } catch (e) {
        cfgObj = {};
      }
    } else if (typeof pCfg === "object" && pCfg !== null) {
      cfgObj = pCfg;
    }
    return {
      id: ev.id,
      key: ev.key,
      name: ev.name,
      active: ev.pivot?.active ?? true,
      run_order: ev.pivot?.run_order ?? null,
      config: cfgObj,
    };
  });
  drawerEdit.value = true;

  item.actions.forEach((a) => {
    form.actions.push({
      name: a.name,
      id: a.id,
    });
  });
};

const closeEditDrawer = () => {
  drawerEdit.value = false;
  form.reset();
};

const openCreateDrawer = () => {
  createForm.reset();
  drawerCreate.value = true;
};

const closeCreateDrawer = () => {
  drawerCreate.value = false;
  createForm.reset();
};

onMounted(() => {
  props.actions.forEach((a) => {
    actionOptions.value.push({
      name: a.name,
      id: a.id,
    });
  });
});

function eventById(id) {
  return (props.availableEvents || []).find((e) => Number(e.id) === Number(id));
}

function eventKey(ev) {
  const id = ev?.id;
  const found = eventById(id);
  return (found?.key || ev?.key || "").toString();
}

function defaultConfigForKey(key) {
  switch (key) {
    case "add_segment":
      return { segment_id: null, deactivate_previous: true };
    case "archive_contract":
      return { archive_setting_id: null, reactivate: false };
    case "end_field_job":
      return {};
    default:
      return {};
  }
}

function adoptKeyAndName(ev) {
  const found = eventById(ev.id);
  if (found) {
    ev.key = found.key;
    ev.name = found.name;
  }
}

function onEventChange(ev) {
  adoptKeyAndName(ev);
  const key = eventKey(ev);
  // Reset config to sensible defaults for the new key
  ev.config = defaultConfigForKey(key);
  // Clear any raw JSON cache
  if (ev.__rawJson !== undefined) delete ev.__rawJson;
}

function defaultEventPayload() {
  const first = (props.availableEvents || [])[0] || { id: null, key: null, name: null };
  return {
    id: first.id || null,
    key: first.key || null,
    name: first.name || null,
    active: true,
    run_order: null,
    config: defaultConfigForKey(first.key || ""),
  };
}

function tryAdoptRaw(ev) {
  try {
    const obj = JSON.parse(ev.__rawJson || "{}");
    if (obj && typeof obj === "object") {
      ev.config = obj;
    }
  } catch (e) {
    // ignore parse error, leave raw as-is
  }
}

const filtered = computed(() => {
  const term = search.value?.toLowerCase() ?? "";
  const tplId = selectedTemplateId.value ? Number(selectedTemplateId.value) : null;
  return (props.decisions || []).filter((d) => {
    const matchesSearch =
      !term ||
      d.name?.toLowerCase().includes(term) ||
      d.color_tag?.toLowerCase().includes(term);
    const matchesAuto = !onlyAutoMail.value || !!d.auto_mail;
    const matchesTemplate = !tplId || Number(d.email_template_id || 0) === tplId;
    return matchesSearch && matchesAuto && matchesTemplate;
  });
});

const update = () => {
  const clientErrors = validateEventsClientSide(form.events || []);
  if (Object.keys(clientErrors).length > 0) {
    // attach errors to form for display
    form.setErrors(clientErrors);
    scrollToFirstEventError(clientErrors, "edit");
    return;
  }

  form.put(route("settings.decisions.update", { id: form.id }), {
    onSuccess: () => {
      closeEditDrawer();
    },
    onError: (errors) => {
      // preserve server errors for display
      scrollToFirstEventError(form.errors, "edit");
    },
  });
};

const store = () => {
  const clientErrors = validateEventsClientSide(createForm.events || []);
  if (Object.keys(clientErrors).length > 0) {
    createForm.setErrors(clientErrors);
    scrollToFirstEventError(clientErrors, "create");
    return;
  }

  createForm.post(route("settings.decisions.store"), {
    onSuccess: () => {
      closeCreateDrawer();
    },
    onError: () => {
      scrollToFirstEventError(createForm.errors, "create");
    },
  });
};

function validateEventsClientSide(events) {
  const errors = {};
  (events || []).forEach((ev, idx) => {
    const key = eventKey(ev);
    if (key === "add_segment") {
      if (!ev.config || !ev.config.segment_id) {
        errors[`events.${idx}.config.segment_id`] = "Izberite segment.";
      }
    } else if (key === "archive_contract") {
      if (!ev.config || !ev.config.archive_setting_id) {
        errors[`events.${idx}.config.archive_setting_id`] = "Izberite nastavitve arhiva.";
      }
    }
  });
  return errors;
}

function scrollToFirstEventError(errorsBag, mode /* 'edit' | 'create' */) {
  const keys = Object.keys(errorsBag || {});
  // find first event-related error key
  const first = keys.find((k) =>
    /^events\.\d+\.config\.(segment_id|archive_setting_id)$/.test(k)
  );
  if (!first) return;
  const match = first.match(/^events\.(\d+)\.config\.(segment_id|archive_setting_id)$/);
  if (!match) return;
  const idx = Number(match[1]);
  const field = match[2];
  let targetId = null;
  if (field === "segment_id") {
    targetId = mode === "create" ? `cseg-${idx}` : `seg-${idx}`;
  } else if (field === "archive_setting_id") {
    targetId = mode === "create" ? `cas-${idx}` : `as-${idx}`;
  }
  if (!targetId) return;
  nextTick(() => {
    const el = document.getElementById(targetId);
    if (el && "scrollIntoView" in el) {
      el.scrollIntoView({ behavior: "smooth", block: "center" });
      // also focus the control for accessibility
      if ("focus" in el) {
        try {
          el.focus();
        } catch (e) {
          /* noop */
        }
      }
    }
  });
}

const eventsValidEdit = computed(() => {
  const errs = validateEventsClientSide(form.events || []);
  return Object.keys(errs).length === 0;
});

const eventsValidCreate = computed(() => {
  const errs = validateEventsClientSide(createForm.events || []);
  return Object.keys(errs).length === 0;
});

const confirmDelete = (decision) => {
  toDelete.value = decision;
  showDelete.value = true;
};

const cancelDelete = () => {
  toDelete.value = null;
  showDelete.value = false;
};

const destroyDecision = () => {
  if (!toDelete.value) return;
  router.delete(route("settings.decisions.destroy", { id: toDelete.value.id }), {
    preserveScroll: true,
    onFinish: () => cancelDelete(),
  });
};
</script>
<template>
  <div class="p-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
    <div class="flex flex-col sm:flex-row gap-2 items-start sm:items-center">
      <TextInput v-model="search" placeholder="Iskanje..." class="w-full sm:w-72" />
      <select
        v-model="selectedTemplateId"
        class="block w-full sm:w-64 border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
      >
        <option :value="null">Vse predloge</option>
        <option v-for="t in emailTemplates" :key="t.id" :value="t.id">
          {{ t.name }}
        </option>
      </select>
      <label class="flex items-center gap-2 text-sm">
        <input
          type="checkbox"
          v-model="onlyAutoMail"
          class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
        />
        Samo auto mail
      </label>
    </div>
    <PrimaryButton @click="openCreateDrawer">+ Dodaj odločitev</PrimaryButton>
  </div>
  <div class="px-4 pb-4">
    <DataTableClient
      :columns="columns"
      :rows="filtered"
      :sort="sort"
      :search="''"
      :page="page"
      :pageSize="pageSize"
      :showToolbar="false"
      @update:sort="(v) => (sort = v)"
      @update:page="(v) => (page = v)"
      @update:pageSize="(v) => (pageSize = v)"
    >
      <template #cell-color_tag="{ row }">
        <div class="flex items-center gap-2">
          <span
            v-if="row.color_tag"
            class="inline-block h-4 w-4 rounded"
            :style="{ backgroundColor: row.color_tag }"
          ></span>
          <span>{{ row.color_tag || "" }}</span>
        </div>
      </template>
      <template #cell-belongs="{ row }">
        {{ row.actions?.length ?? 0 }}
      </template>
      <template #cell-events="{ row }">
        <div class="flex items-center gap-2">
          <span class="text-sm text-gray-600">{{ row.events?.length ?? 0 }}</span>
          <Dropdown align="left" width="64" :close-on-content-click="false">
            <template #trigger>
              <button
                type="button"
                class="p-1 rounded hover:bg-gray-100 border border-transparent hover:border-gray-200"
              >
                <DottedMenu size="sm" css="text-gray-600" />
              </button>
            </template>
            <template #content>
              <div class="py-2">
                <div
                  v-if="!row.events || row.events.length === 0"
                  class="px-3 py-1 text-sm text-gray-500"
                >
                  Ni dogodkov
                </div>
                <ul v-else class="max-h-64 overflow-auto">
                  <li
                    v-for="(ev, i) in row.events"
                    :key="ev.id"
                    class="px-3 py-1 text-sm flex items-center gap-2"
                  >
                    <span
                      class="inline-flex items-center justify-center w-2 h-2 rounded-full"
                      :class="ev.pivot?.active === false ? 'bg-gray-300' : 'bg-green-500'"
                    ></span>
                    <span
                      class="text-gray-800"
                      :class="
                        ev.pivot?.active === false ? 'line-through text-gray-400' : ''
                      "
                    >
                      {{ ev.pivot?.run_order ?? i + 1 }}.
                      {{ ev.name || ev.key || "#" + ev.id }}
                    </span>
                  </li>
                </ul>
              </div>
            </template>
          </Dropdown>
        </div>
      </template>
      <template #cell-auto_mail="{ row }">
        <div class="flex flex-col text-sm">
          <span :class="row.auto_mail ? 'text-green-700' : 'text-gray-500'">{{
            row.auto_mail ? "Enabled" : "Disabled"
          }}</span>
          <span v-if="row.auto_mail && row.email_template_id" class="text-gray-600">
            Template:
            {{ emailTemplates.find((t) => t.id === row.email_template_id)?.name || "—" }}
          </span>
        </div>
      </template>
      <template #actions="{ row }">
        <button class="px-2" @click="openEditDrawer(row)">
          <EditIcon size="md" css="text-gray-500" />
        </button>
        <button
          class="px-2 disabled:opacity-40"
          :disabled="(row.activities_count ?? 0) > 0"
          @click="confirmDelete(row)"
        >
          <TrashBinIcon size="md" css="text-red-500" />
        </button>
      </template>
    </DataTableClient>
  </div>
  <DialogModal :show="drawerEdit" @close="closeEditDrawer">
    <template #title>
      <span>Spremeni odločitev</span>
    </template>
    <template #content>
      <form @submit.prevent="update">
        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="name" value="Ime" />
          <TextInput
            id="name"
            v-model="form.name"
            type="text"
            class="mt-1 block w-full"
            autocomplete="name"
          />
        </div>

        <div class="mt-4 flex items-center gap-2">
          <input
            id="autoMailEdit"
            type="checkbox"
            v-model="form.auto_mail"
            class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
          />
          <label for="autoMailEdit" class="text-sm">Samodejna pošta (auto mail)</label>
        </div>

        <div class="col-span-6 sm:col-span-4 mt-2">
          <InputLabel for="emailTemplateEdit" value="Email predloga" />
          <select
            id="emailTemplateEdit"
            v-model="form.email_template_id"
            :disabled="!form.auto_mail"
            class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <option :value="null">— Brez —</option>
            <option v-for="t in emailTemplates" :key="t.id" :value="t.id">
              {{ t.name }}
            </option>
          </select>
          <p v-if="form.email_template_id" class="text-xs text-gray-500 mt-1">
            <span
              v-if="
                (
                  emailTemplates.find((t) => t.id === form.email_template_id)
                    ?.entity_types || []
                ).includes('contract')
              "
              >Ta predloga zahteva pogodbo.</span
            >
          </p>
        </div>
        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="colorTag" value="Barva" />
          <div class="mt-1">
            <InlineColorPicker v-model="form.color_tag" />
          </div>
        </div>

        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="actionsSelect" value="Akcije" />
          <multiselect
            id="actionsSelect"
            v-model="form.actions"
            :options="actionOptions"
            :multiple="true"
            track-by="id"
            :taggable="true"
            placeholder="Dodaj akcijo"
            :append-to-body="true"
            label="name"
          />
        </div>

        <!-- Quick JSON event config editor -->
        <div class="mt-6">
          <h3 class="text-md font-semibold mb-2">Dogodki odločitve</h3>
          <div class="space-y-4">
            <div v-for="(ev, idx) in form.events" :key="idx" class="border rounded p-3">
              <div class="flex flex-col sm:flex-row gap-3">
                <div class="flex-1">
                  <InputLabel :for="`event-${idx}`" value="Dogodek" />
                  <select
                    :id="`event-${idx}`"
                    v-model.number="ev.id"
                    class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
                    @change="onEventChange(ev)"
                  >
                    <option :value="null">— Izberi —</option>
                    <option v-for="opt in availableEvents" :key="opt.id" :value="opt.id">
                      {{ opt.name || opt.key || `#${opt.id}` }}
                    </option>
                  </select>
                </div>
                <div class="w-36">
                  <InputLabel :for="`order-${idx}`" value="Vrstni red" />
                  <TextInput
                    :id="`order-${idx}`"
                    v-model.number="ev.run_order"
                    type="number"
                    class="w-full"
                  />
                </div>
                <div class="flex items-end gap-2">
                  <label class="flex items-center gap-2 text-sm">
                    <input
                      type="checkbox"
                      v-model="ev.active"
                      class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
                    />
                    Aktivno
                  </label>
                  <button
                    type="button"
                    class="text-red-600 text-sm"
                    @click="form.events.splice(idx, 1)"
                  >
                    Odstrani
                  </button>
                </div>
              </div>
              <div class="mt-3">
                <template v-if="eventKey(ev) === 'add_segment'">
                  <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div>
                      <InputLabel :for="`seg-${idx}`" value="Segment" />
                      <select
                        :id="`seg-${idx}`"
                        v-model.number="ev.config.segment_id"
                        class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
                      >
                        <option :value="null">— Izberi segment —</option>
                        <option v-for="s in segments" :key="s.id" :value="s.id">
                          {{ s.name }}
                        </option>
                      </select>
                      <p
                        v-if="form.errors[`events.${idx}.config.segment_id`]"
                        class="text-xs text-red-600 mt-1"
                      >
                        {{ form.errors[`events.${idx}.config.segment_id`] }}
                      </p>
                    </div>
                    <div class="flex items-end">
                      <label class="flex items-center gap-2 text-sm mt-6">
                        <input
                          type="checkbox"
                          v-model="ev.config.deactivate_previous"
                          class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
                        />
                        Deaktiviraj prejšnje
                      </label>
                    </div>
                  </div>
                </template>
                <template v-else-if="eventKey(ev) === 'archive_contract'">
                  <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div>
                      <InputLabel :for="`as-${idx}`" value="Archive setting" />
                      <select
                        :id="`as-${idx}`"
                        v-model.number="ev.config.archive_setting_id"
                        class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
                      >
                        <option :value="null">— Izberi nastavitev —</option>
                        <option v-for="a in archiveSettings" :key="a.id" :value="a.id">
                          {{ a.name }}
                        </option>
                      </select>
                      <p
                        v-if="form.errors[`events.${idx}.config.archive_setting_id`]"
                        class="text-xs text-red-600 mt-1"
                      >
                        {{ form.errors[`events.${idx}.config.archive_setting_id`] }}
                      </p>
                    </div>
                    <div class="flex items-end">
                      <label class="flex items-center gap-2 text-sm mt-6">
                        <input
                          type="checkbox"
                          v-model="ev.config.reactivate"
                          class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
                        />
                        Reactivate namesto arhiva
                      </label>
                    </div>
                  </div>
                </template>
                <template v-else-if="eventKey(ev) === 'end_field_job'">
                  <p class="text-sm text-gray-600">
                    Ta dogodek nima dodatnih nastavitev.
                  </p>
                </template>
                <template v-else>
                  <!-- Fallback advanced editor for unknown event keys -->
                  <InputLabel :for="`cfg-${idx}`" value="Napredna nastavitev (JSON)" />
                  <textarea
                    :id="`cfg-${idx}`"
                    v-model="ev.__rawJson"
                    @focus="
                      ev.__rawJson =
                        ev.__rawJson ?? JSON.stringify(ev.config || {}, null, 2)
                    "
                    @change="tryAdoptRaw(ev)"
                    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 text-sm font-mono"
                    rows="6"
                    placeholder="{ }"
                  ></textarea>
                </template>
              </div>
            </div>
            <div>
              <PrimaryButton
                type="button"
                @click="form.events.push(defaultEventPayload())"
                >+ Dodaj dogodek</PrimaryButton
              >
            </div>
          </div>
        </div>

        <div class="flex justify-end mt-6">
          <ActionMessage :on="form.recentlySuccessful" class="me-3">
            Shranjuje.
          </ActionMessage>

          <PrimaryButton
            :class="{ 'opacity-25': form.processing || !eventsValidEdit }"
            :disabled="form.processing || !eventsValidEdit"
          >
            Shrani
          </PrimaryButton>
        </div>
      </form>
    </template>
  </DialogModal>

  <DialogModal :show="drawerCreate" @close="closeCreateDrawer">
    <template #title>
      <span>Dodaj odločitev</span>
    </template>
    <template #content>
      <form @submit.prevent="store">
        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="nameCreate" value="Ime" />
          <TextInput
            id="nameCreate"
            v-model="createForm.name"
            type="text"
            class="mt-1 block w-full"
            autocomplete="name"
          />
        </div>

        <div class="mt-4 flex items-center gap-2">
          <input
            id="autoMailCreate"
            type="checkbox"
            v-model="createForm.auto_mail"
            class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
          />
          <label for="autoMailCreate" class="text-sm">Samodejna pošta (auto mail)</label>
        </div>

        <div class="col-span-6 sm:col-span-4 mt-2">
          <InputLabel for="emailTemplateCreate" value="Email predloga" />
          <select
            id="emailTemplateCreate"
            v-model="createForm.email_template_id"
            :disabled="!createForm.auto_mail"
            class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <option :value="null">— Brez —</option>
            <option v-for="t in emailTemplates" :key="t.id" :value="t.id">
              {{ t.name }}
            </option>
          </select>
          <p v-if="createForm.email_template_id" class="text-xs text-gray-500 mt-1">
            <span
              v-if="
                (
                  emailTemplates.find((t) => t.id === createForm.email_template_id)
                    ?.entity_types || []
                ).includes('contract')
              "
              >Ta predloga zahteva pogodbo.</span
            >
          </p>
        </div>
        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="colorTagCreate" value="Barva" />
          <div class="mt-1">
            <InlineColorPicker v-model="createForm.color_tag" />
          </div>
        </div>

        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="actionsCreate" value="Akcije" />
          <multiselect
            id="actionsCreate"
            v-model="createForm.actions"
            :options="actionOptions"
            :multiple="true"
            track-by="id"
            :taggable="true"
            placeholder="Dodaj akcijo"
            :append-to-body="true"
            label="name"
          />
        </div>

        <!-- Create: Decision events editor -->
        <div class="mt-6">
          <h3 class="text-md font-semibold mb-2">Dogodki odločitve</h3>
          <div class="space-y-4">
            <div
              v-for="(ev, idx) in createForm.events"
              :key="`c-${idx}`"
              class="border rounded p-3"
            >
              <div class="flex flex-col sm:flex-row gap-3">
                <div class="flex-1">
                  <InputLabel :for="`cevent-${idx}`" value="Dogodek" />
                  <select
                    :id="`cevent-${idx}`"
                    v-model.number="ev.id"
                    class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
                    @change="onEventChange(ev)"
                  >
                    <option :value="null">— Izberi —</option>
                    <option v-for="opt in availableEvents" :key="opt.id" :value="opt.id">
                      {{ opt.name || opt.key || `#${opt.id}` }}
                    </option>
                  </select>
                </div>
                <div class="w-36">
                  <InputLabel :for="`corder-${idx}`" value="Vrstni red" />
                  <TextInput
                    :id="`corder-${idx}`"
                    v-model.number="ev.run_order"
                    type="number"
                    class="w-full"
                  />
                </div>
                <div class="flex items-end gap-2">
                  <label class="flex items-center gap-2 text-sm">
                    <input
                      type="checkbox"
                      v-model="ev.active"
                      class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
                    />
                    Aktivno
                  </label>
                  <button
                    type="button"
                    class="text-red-600 text-sm"
                    @click="createForm.events.splice(idx, 1)"
                  >
                    Odstrani
                  </button>
                </div>
              </div>
              <div class="mt-3">
                <template v-if="eventKey(ev) === 'add_segment'">
                  <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div>
                      <InputLabel :for="`cseg-${idx}`" value="Segment" />
                      <select
                        :id="`cseg-${idx}`"
                        v-model.number="ev.config.segment_id"
                        class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
                      >
                        <option :value="null">— Izberi segment —</option>
                        <option v-for="s in segments" :key="s.id" :value="s.id">
                          {{ s.name }}
                        </option>
                      </select>
                      <p
                        v-if="createForm.errors[`events.${idx}.config.segment_id`]"
                        class="text-xs text-red-600 mt-1"
                      >
                        {{ createForm.errors[`events.${idx}.config.segment_id`] }}
                      </p>
                    </div>
                    <div class="flex items-end">
                      <label class="flex items-center gap-2 text-sm mt-6">
                        <input
                          type="checkbox"
                          v-model="ev.config.deactivate_previous"
                          class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
                        />
                        Deaktiviraj prejšnje
                      </label>
                    </div>
                  </div>
                </template>
                <template v-else-if="eventKey(ev) === 'archive_contract'">
                  <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div>
                      <InputLabel :for="`cas-${idx}`" value="Archive setting" />
                      <select
                        :id="`cas-${idx}`"
                        v-model.number="ev.config.archive_setting_id"
                        class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
                      >
                        <option :value="null">— Izberi nastavitev —</option>
                        <option v-for="a in archiveSettings" :key="a.id" :value="a.id">
                          {{ a.name }}
                        </option>
                      </select>
                      <p
                        v-if="
                          createForm.errors[`events.${idx}.config.archive_setting_id`]
                        "
                        class="text-xs text-red-600 mt-1"
                      >
                        {{ createForm.errors[`events.${idx}.config.archive_setting_id`] }}
                      </p>
                    </div>
                    <div class="flex items-end">
                      <label class="flex items-center gap-2 text-sm mt-6">
                        <input
                          type="checkbox"
                          v-model="ev.config.reactivate"
                          class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
                        />
                        Reactivate namesto arhiva
                      </label>
                    </div>
                  </div>
                </template>
                <template v-else-if="eventKey(ev) === 'end_field_job'">
                  <p class="text-sm text-gray-600">
                    Ta dogodek nima dodatnih nastavitev.
                  </p>
                </template>
                <template v-else>
                  <InputLabel :for="`ccfg-${idx}`" value="Napredna nastavitev (JSON)" />
                  <textarea
                    :id="`ccfg-${idx}`"
                    v-model="ev.__rawJson"
                    @focus="
                      ev.__rawJson =
                        ev.__rawJson ?? JSON.stringify(ev.config || {}, null, 2)
                    "
                    @change="tryAdoptRaw(ev)"
                    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 text-sm font-mono"
                    rows="6"
                    placeholder="{ }"
                  ></textarea>
                </template>
              </div>
            </div>
            <div>
              <PrimaryButton
                type="button"
                @click="createForm.events.push(defaultEventPayload())"
                >+ Dodaj dogodek</PrimaryButton
              >
            </div>
          </div>
        </div>

        <div class="flex justify-end mt-4">
          <ActionMessage :on="createForm.recentlySuccessful" class="me-3">
            Shranjuje.
          </ActionMessage>

          <PrimaryButton
            :class="{ 'opacity-25': createForm.processing || !eventsValidCreate }"
            :disabled="createForm.processing || !eventsValidCreate"
          >
            Dodaj
          </PrimaryButton>
        </div>
      </form>
    </template>
  </DialogModal>

  <ConfirmationModal :show="showDelete" @close="cancelDelete">
    <template #title> Delete decision </template>
    <template #content>
      Are you sure you want to delete decision "{{ toDelete?.name }}"? This cannot be
      undone.
    </template>
    <template #footer>
      <button
        @click="cancelDelete"
        class="px-4 py-2 rounded bg-gray-200 hover:bg-gray-300 me-2"
      >
        Cancel
      </button>
      <PrimaryButton @click="destroyDecision">Delete</PrimaryButton>
    </template>
  </ConfirmationModal>
</template>
