<script setup>
import { computed } from "vue";
import ConfirmationDialog from "@/components/ConfirmationDialog.vue";

const props = defineProps({
  visible: { type: Boolean, default: false },
  conflict: { type: Object, default: null },
  mode: {
    type: String,
    default: "restore_deleted",
    validator: (v) => ["restore_deleted", "replace_existing"].includes(v),
  },
  resourceLabel: { type: String, default: "record" },
});

const emit = defineEmits(["update:visible", "confirm", "cancel"]);

const title = computed(() => {
  if (props.mode === "replace_existing") {
    return "Replace existing record?";
  }
  return "Restore deleted record?";
});

const message = computed(() => {
  const slug = props.conflict?.slug || "";
  const trashed = props.conflict?.trashed;
  const live = props.conflict?.live;
  const trashedTitle =
    trashed?.title || trashed?.name || props.resourceLabel;
  const liveTitle = live?.title || live?.name || props.resourceLabel;

  if (props.mode === "replace_existing" && live) {
    return `A live ${props.resourceLabel} "${liveTitle}" already uses slug "${slug}". Restoring "${trashedTitle}" will replace the live record's content. Continue?`;
  }

  return `A deleted ${props.resourceLabel} "${trashedTitle}" already uses slug "${slug}". Restore it with your new changes?`;
});

const severity = computed(() =>
  props.mode === "replace_existing" ? "warning" : "info",
);

function onConfirm() {
  emit("confirm");
  emit("update:visible", false);
}

function onCancel() {
  emit("cancel");
  emit("update:visible", false);
}
</script>

<template>
  <ConfirmationDialog
    :visible="visible"
    :title="title"
    :message="message"
    :severity="severity"
    confirm-label="Continue"
    cancel-label="Cancel"
    @update:visible="$emit('update:visible', $event)"
    @confirm="onConfirm"
    @cancel="onCancel"
  />
</template>
