<script setup>
import { ref, computed } from "vue";
import { api } from "../api";
import { formatDate } from "../lib/format.js";
import { applyAttachment } from "../lib/attachment.js";
import { t, tSplit } 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 },
  check: { type: Object, default: null },
});
const emit = defineEmits(["saved", "close"]);

const isEdit = !!props.check;
const saving = ref(false);
const error = ref("");
const form = ref({
  date: props.check ? toDateInput(props.check.date) : new Date().toISOString().slice(0, 10),
  result: props.check?.result ?? "passed",
  validUntil: props.check?.validUntil ? toDateInput(props.check.validUntil) : "",
  cost: props.check?.cost || "",
  station: props.check?.station ?? "",
  notes: props.check?.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);
}

// What the server will derive if valid-until is left blank, shown so the effect
// of leaving it empty is visible before saving rather than after.
const derivedNext = computed(() => {
  if (form.value.result === "failed" || !form.value.date) return null;
  const days = props.car?.technicalCheckIntervalDays || 365;
  const d = new Date(form.value.date);
  if (isNaN(d)) return null;
  d.setDate(d.getDate() + days);
  return { days, date: formatDate(d.toISOString()) };
});

async function submit() {
  saving.value = true;
  error.value = "";
  try {
    const payload = {
      car: props.carId,
      date: new Date(form.value.date).toISOString(),
      result: form.value.result,
      // Blank means "derive it from the car's interval" — send null, not a date,
      // so clearing the field on an edit actually removes the override.
      validUntil: form.value.validUntil ? new Date(form.value.validUntil).toISOString() : null,
      cost: form.value.cost ? Number(form.value.cost) : 0,
      station: form.value.station.trim(),
      notes: form.value.notes.trim(),
    };
    const saved = isEdit
      ? await api.updateTechnicalCheck(props.check.id, payload)
      : await api.createTechnicalCheck(payload);
    emit("saved", await applyAttachment(api.files.technical, saved, {
      file: file.value,
      remove: removeFile.value,
    }));
  } catch (e) {
    error.value = e.message;
  } finally {
    saving.value = false;
  }
}
</script>

<template>
  <Modal :title="isEdit ? t('forms.technical.editTitle') : t('forms.technical.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.technical.date") }}</label>
          <DateField v-model="form.date" required />
        </div>
        <div>
          <label class="dh-label">{{ t("forms.technical.result") }}</label>
          <select v-model="form.result" class="dh-input">
            <option value="passed">{{ t("forms.technical.passed") }}</option>
            <option value="failed">{{ t("forms.technical.failed") }}</option>
          </select>
        </div>
      </div>

      <div>
        <label class="dh-label">{{ t("forms.technical.validUntil") }}</label>
        <DateField v-model="form.validUntil" />
        <p v-if="form.result === 'failed'" class="mt-1 text-xs text-muted">
          {{ t("forms.technical.failedHint") }}
        </p>
        <p v-else-if="derivedNext" class="mt-1 text-xs text-muted">
          {{ tSplit("forms.technical.derivedHint", "date", { days: derivedNext.days }).before
          }}<span class="data">{{ derivedNext.date }}</span>{{ tSplit("forms.technical.derivedHint", "date", { days: derivedNext.days }).after }}
        </p>
      </div>

      <div class="grid grid-cols-2 gap-2">
        <div>
          <label class="dh-label">{{ t("forms.technical.cost") }}</label>
          <input v-model="form.cost" type="number" step="0.01" min="0" placeholder="99" class="dh-input data" />
        </div>
        <div>
          <label class="dh-label">{{ t("forms.technical.station") }}</label>
          <input v-model="form.station" :placeholder="t('forms.technical.stationPlaceholder')" class="dh-input" />
        </div>
      </div>

      <AttachmentField
        v-model:file="file"
        v-model:remove="removeFile"
        :record="check"
        :legend="t('forms.technical.attachmentLegend')"
      />

      <div>
        <label class="dh-label">{{ t("forms.technical.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" class="dh-btn dh-btn-primary">
          {{ saving ? t("common.saving") : isEdit ? t("common.saveChanges") : t("forms.technical.submit") }}
        </button>
      </div>
    </form>
  </Modal>
</template>
