<script setup>
import { ref, computed } from "vue";
import { api } from "../api";
import { formatKm } from "../lib/format.js";
import { t } from "../i18n";
import DateField from "./DateField.vue";
import Modal from "./Modal.vue";

const props = defineProps({
  carId: { type: String, required: true },
  car: { type: Object, default: null },
  reminder: { type: Object, default: null },
});
const emit = defineEmits(["saved", "close"]);

const isEdit = !!props.reminder;
const saving = ref(false);
const error = ref("");

const TYPE_VALUES = ["maintenance", "document", "service", "inspection", "other"];

const form = ref({
  title: props.reminder?.title ?? "",
  type: props.reminder?.type ?? "maintenance",
  dueDate: props.reminder?.dueDate ? toDateInput(props.reminder.dueDate) : "",
  dueKm: props.reminder?.dueKm || "",
  repeatDays: props.reminder?.repeatDays || "",
  repeatKm: props.reminder?.repeatKm || "",
  notes: props.reminder?.notes ?? "",
});

function toDateInput(value) {
  const d = new Date(value);
  return isNaN(d) ? "" : d.toISOString().slice(0, 10);
}

// Mirrors the server's rule: a reminder with neither trigger would never fire.
const hasTrigger = computed(() => !!form.value.dueDate || Number(form.value.dueKm) > 0);
const isRecurring = computed(() => Number(form.value.repeatDays) > 0 || Number(form.value.repeatKm) > 0);

async function submit() {
  if (!hasTrigger.value) {
    error.value = t("forms.reminder.noTrigger");
    return;
  }
  saving.value = true;
  error.value = "";
  try {
    const saved = await (isEdit
      ? api.updateReminder(props.reminder.id, payload())
      : api.createReminder(payload()));
    emit("saved", saved);
  } catch (e) {
    error.value = e.message;
  } finally {
    saving.value = false;
  }
}

function payload() {
  return {
    car: props.carId,
    title: form.value.title.trim(),
    type: form.value.type,
    dueDate: form.value.dueDate ? new Date(form.value.dueDate).toISOString() : null,
    dueKm: form.value.dueKm ? Number(form.value.dueKm) : 0,
    repeatDays: form.value.repeatDays ? Number(form.value.repeatDays) : 0,
    repeatKm: form.value.repeatKm ? Number(form.value.repeatKm) : 0,
    // Editing never silently closes a reminder; that is what Done does.
    done: props.reminder?.done ?? false,
    notes: form.value.notes.trim(),
  };
}
</script>

<template>
  <Modal :title="isEdit ? t('forms.reminder.editTitle') : t('forms.reminder.addTitle')" @close="emit('close')">
    <p v-if="error" class="mb-3 rounded-control bg-danger-soft px-3 py-2 text-sm font-medium text-danger">{{ error }}</p>
    <form class="space-y-3" @submit.prevent="submit">
      <div>
        <label class="dh-label">{{ t("forms.reminder.title") }}</label>
        <input v-model="form.title" required :placeholder="t('forms.reminder.titlePlaceholder')" class="dh-input" />
      </div>

      <div>
        <label class="dh-label">{{ t("forms.reminder.type") }}</label>
        <select v-model="form.type" class="dh-input">
          <option v-for="v in TYPE_VALUES" :key="v" :value="v">{{ t(`enums.reminderType.${v}`) }}</option>
        </select>
      </div>

      <fieldset class="rounded-control border border-subtle p-3">
        <legend class="eyebrow px-1">{{ t("forms.reminder.remindMe") }}</legend>
        <div class="grid grid-cols-2 gap-2">
          <div>
            <label class="dh-label">{{ t("forms.reminder.onDate") }}</label>
            <DateField v-model="form.dueDate" />
          </div>
          <div>
            <label class="dh-label">{{ t("forms.reminder.atOdometer") }}</label>
            <input v-model="form.dueKm" type="number" min="0" placeholder="30000" class="dh-input data" />
          </div>
        </div>
        <p class="mt-1.5 text-xs text-muted">
          {{ t("forms.reminder.triggerHint") }}
          <span v-if="car?.currentKm != null"> {{ t("forms.reminder.currentKm", { km: formatKm(car.currentKm) }) }}</span>
        </p>
      </fieldset>

      <fieldset class="rounded-control border border-subtle p-3">
        <legend class="eyebrow px-1">{{ t("forms.reminder.repeat") }}</legend>
        <div class="grid grid-cols-2 gap-2">
          <div>
            <label class="dh-label">{{ t("forms.reminder.everyDays") }}</label>
            <input v-model="form.repeatDays" type="number" min="0" placeholder="365" class="dh-input data" />
          </div>
          <div>
            <label class="dh-label">{{ t("forms.reminder.everyKm") }}</label>
            <input v-model="form.repeatKm" type="number" min="0" placeholder="15000" class="dh-input data" />
          </div>
        </div>
        <p class="mt-1.5 text-xs text-muted">
          {{ isRecurring ? t("forms.reminder.recurringHint") : t("forms.reminder.oneOffHint") }}
        </p>
      </fieldset>

      <div>
        <label class="dh-label">{{ t("forms.reminder.notes") }}</label>
        <input v-model="form.notes" class="dh-input" />
      </div>

      <div class="mt-4 flex justify-end gap-2">
        <button type="button" class="dh-btn dh-btn-ghost" @click="emit('close')">{{ t("common.cancel") }}</button>
        <button type="submit" :disabled="saving || !hasTrigger" class="dh-btn dh-btn-primary">
          {{ saving ? t("common.saving") : isEdit ? t("common.saveChanges") : t("forms.reminder.submit") }}
        </button>
      </div>
    </form>
  </Modal>
</template>
