<script setup>
import { ref } from "vue";
import { api } from "../api";
import { formatKm } from "../lib/format.js";
import { applyAttachment } from "../lib/attachment.js";
import { SERVICE_PARTS, visibleParts } from "../lib/serviceParts.js";
import { t } from "../i18n";
import AttachmentField from "./AttachmentField.vue";
import DateField from "./DateField.vue";
import Modal from "./Modal.vue";

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

const isEdit = !!props.service;
const saving = ref(false);
const error = ref("");
// The parts this car records. Read once rather than as a computed: the dialog is
// mounted per open, and a part switching off under an open form would rearrange
// it mid-edit.
const shown = visibleParts(props.car);
const hidden = SERVICE_PARTS.filter((part) => !shown.includes(part)).map((part) => part.key);
const form = ref({
  date: props.service ? toDateInput(props.service.date) : new Date().toISOString().slice(0, 10),
  km: props.service?.km ?? "",
  // One entry per part, built from the shared list rather than named here, so a
  // part added to it turns up in this dialog without a second edit. An existing
  // record written before a part existed has no field for it, which reads as
  // unchecked.
  //
  // Every part, not only the shown ones: an edit has to send back what a hidden
  // part already said, because the API rewrites all three booleans from the body
  // and an omitted one would come back false. A *new* record starts a hidden
  // part at false rather than its `initial`, since ticking a box nobody was
  // shown is not a default, it's a guess.
  ...Object.fromEntries(
    SERVICE_PARTS.map((part) => [
      part.field,
      props.service
        ? !!props.service[part.field]
        : part.initial && !hidden.includes(part.key),
    ])
  ),
  notes: props.service?.notes ?? "",
});

const file = ref(null);
const removeFile = ref(false);

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

async function submit() {
  saving.value = true;
  error.value = "";
  try {
    const payload = {
      car: props.carId,
      date: new Date(form.value.date).toISOString(),
      // Blank-tested, not truthiness-tested: a service logged at 0 km on a car
      // collected new is a real entry, and the field is required anyway.
      km: form.value.km === "" ? 0 : Number(form.value.km),
      ...Object.fromEntries(SERVICE_PARTS.map((part) => [part.field, form.value[part.field]])),
      notes: form.value.notes.trim(),
    };
    const saved = isEdit
      ? await api.updateService(props.service.id, payload)
      : await api.createService(payload);
    emit("saved", await applyAttachment(api.files.services, saved, {
      file: file.value,
      remove: removeFile.value,
    }));
  } catch (e) {
    error.value = e.message;
  } finally {
    saving.value = false;
  }
}
</script>

<template>
  <Modal :title="isEdit ? t('forms.service.editTitle') : t('forms.service.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 class="grid grid-cols-2 gap-2">
        <div>
          <label class="dh-label">{{ t("forms.service.date") }}</label>
          <DateField v-model="form.date" required />
        </div>
        <div>
          <label class="dh-label">{{ t("forms.service.odometer") }}</label>
          <input v-model="form.km" type="number" min="0" required placeholder="16138" class="dh-input data" />
        </div>
      </div>
      <fieldset v-if="shown.length" class="rounded-control border border-subtle p-3">
        <legend class="eyebrow px-1">{{ t("forms.service.changedParts") }}</legend>
        <label
          v-for="part in shown"
          :key="part.key"
          class="flex items-center gap-2 py-1 text-sm text-body"
        >
          <input type="checkbox" v-model="form[part.field]" class="accent-[var(--accent)]" />
          {{ t(part.label) }}
        </label>
      </fieldset>
      <AttachmentField
        v-model:file="file"
        v-model:remove="removeFile"
        :record="service"
        :legend="t('forms.service.attachmentLegend')"
      />
      <div>
        <label class="dh-label">{{ t("forms.service.notes") }}</label>
        <input v-model="form.notes" class="dh-input" />
      </div>
      <p v-if="car" class="text-xs text-muted">
        {{ t("forms.service.autoHint", { days: car.serviceIntervalDays, km: formatKm(car.serviceIntervalKm) }) }}
      </p>
      <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" class="dh-btn dh-btn-primary">
          {{ saving ? t("common.saving") : isEdit ? t("common.saveChanges") : t("forms.service.submit") }}
        </button>
      </div>
    </form>
  </Modal>
</template>
